Title: Building Web Applications With The Struts Framework
1- Building Web Applications With The Struts
Framework - Session WE06 11/20/2002 1000-1100
- Craig R. McClanahan
- Senior Staff Engineer
- Sun Microsystems, Inc.
2Session Outline
- Web Applications Backgrounder
- The Model-View-Controller Architecture
- The Struts Framework
- Building A Web Application With Struts
- Resources
3- Web Applications Backgrounder
4Web Applications Backgrounder
- Web applications run over the HTTP protocol
- Request/response oriented
- Stateless
- Web applications use varied presentation (markup)
languages, and talk to varied client hardware
devices - Standard HTML -- not!
- Varying dynamic and JavaScript capabilities
- Wireless devices vary in capabilities, language
dialect, and input device support
5Simple Solutions ... for Simple Problems
- For relatively simple applications, a simple
architecture works fine - For each page in the user interface ...
- Create a servlet, JSP page, or something similar
- The page includes
- Logic to create the user interface
- Logic to retrieve required information from the
database - Logic to perform the appropriate business
transaction - Logic to update the corresponding database
information - And it's all mixed together in one source file
- This works fine for a Guest Book app, but what
about something bigger?
6What About Large Scale Applications?
- Disparate skill sets required
- Presentation Layer-- User interface design,
visual appearance, interaction model - Application Layer Functional business logic to
perform required transactions - Persistence Layer Databases, directory servers,
messaging, Enterprise JavaBeansTM (EJBs) - Application Deployment Networks, firewalls,
public key infrastructures, load balancing,
failover - We need a fundamental organizing principle
- The Model-View-Controller (MVC) architecture
7- The Model-View-Controller (MVC) Architecture
8The Model-View-Controller Architecture
- Divides the overall functionality of an
application into three layers - Model Layer Contains the functional business
logic of the application, as well as a
representation of the persistently stored data
backing the application - View Layer Contains the user interface,
including mechanisms to accept user input and
render results - Controller Layer Contains the logic that
manages the flow of individual requests,
dispatching to the appropriate business logic
component
9The Model Layer
- Functional business logic
- Should be modelled as JavaBeans or Session EJBs
- Should be reusable in non-web environments
- API exposes public methods for each logical unit
of work (while hiding the details) - Persistent data storage
- Should manage permanent storage of application
data - Typically shared across many applications
- API should expose data retrieval and storage
operations (while hiding the mechanisms)
10The View Layer
- Creation of the user interface
- Typically in HTML or an XML-based dialect
- Normally a combination of static and dynamic
content - Actual content varies depending on
- Device or browser type
- User preferences / personalization
- Internationalization and localization
requirements - Accessibility requirements
11The Controller Layer
- Incoming requests flow through a common path
- Received by common component
- Standardized request pre-processing
- Dispatch to request-specific model component
(business logic) - Forward to business-logic-specified view
component - Standardized request post-processing
- Often called Model 2 Design in the JSP/Servlet
community - In modern design pattern terminology, Struts
implements the front controller pattern.
12- The Struts Framework An Implementation of the
MVC Architecture
13The Struts Framework Architecture
14The Struts Framework Model Layer
- Struts does not restrict implementation
techniques for model layer - JDBC-accessed databases
- Enterprise JavaBeans
- O-R mapping tools
- Optional JDBC connection pool available
- Common design pattern
- Action acquires information from persistence tier
- Exposes information as request/session attributes
- View layer pulls data from attributes for display
15The Struts Framework View Layer
- Form Bean maintains state of form input fields
across requests - ActionForm Standard JavaBean design pattern
- DynaActionForm Property names and types defined
in Struts configuration file - In addition to properties, form beans define two
standard methods - reset() -- Reset form properties to initial state
- validate() -- Perform field-level validations
- Form bean properties are typically Strings
- Allows redisplay of invalid input
16The Struts Framework View Layer
- Internationalization Support enables
locale-specific applications - Locale Standard Java class representing a
choice of language and/or country - MessageFormat Standard Java class representing
an individual message with replaceable
parameters - 0 is not a valid credit rating
- MessageResources Struts abstraction around sets
of messages for supported locales - ActionErrors / ActionMessages Struts
collections of localized messages
17The Struts Framework View Layer
- JSP Custom Tag Libraries If you are using JSP
pages for your presentation - struts-bean.tld Fundamental bean manipulation
and internationalization - struts-html.tld Smart HTML elements
- struts-logic.tld Basic conditionals and
iteration - struts-template.tld Basic layout management
18The Struts Framework View Layer
- Standard tag libraries added in Struts 1.1
- struts-nested.tld -- Nested variants of
standard tags that resolve relative references
against beans - struts-tiles.tld Full features layout
management library - Contributed libraries added in Struts 1.1
- struts-xxx-el.tld Versions of standard Struts
tag libraries that support the expression
language syntax of JSP Standard Tag Library
19The Struts Framework View Layer
- Validation Framework
- No-code-required field level validations
- Configured in an XML document included in the web
application - Optionally generates client side JavaScript to
enforce validation rules - Extensible architecture
20The Struts Framework Controller Layer
- ActionServlet Standard implementation of
controller - At application startup, reads configuration file
and initializes resources - Struts 1.1 PlugIn General start/stop hook
- On each request, implements the standard Struts
request processing lifecycle (in Struts 1.1,
implemented in RequestProcessor) - Specialization / customization via subclassing
- Struts 1.1 Sub-application modules support
21The Struts Framework Controller Layer
- Action Standard base class for business logic
components and adapters - Mapped to logical names by request processor
- Single instance per application (must be thread
safe) - Instantiated as needed, like servlets
- Implements the Command Pattern
- execute() -- Invoked for each request
- Can (but typically does not) create response
content directly - Typically returns ActionForward to select
resource to prepare response
22The Struts Framework Controller Layer
- Standard Request Processing Lifecycle 1
- processLocale() -- Record user's locale
preference (if not already present) - processPreprocess() -- general purpose
pre-processing hook - processMapping() -- select Action to be utilized
- processRoles() -- perform security role-based
restrictions on action execution - processActionForm() -- Create or acquire an
appropriate ActionForm instance
23The Struts Framework Controller Layer
- Standard Request Processing Lifecycle 2
- processPopulate() -- Copy the request parameters
into the form bean properties - processValidate() -- Call form bean's validate()
method - processActionCreate() -- Create or acquire an
appropriate Action instance - processActionPerform() -- Call action's execute()
method - processActionForward() -- Process returned
ActionForward instance (if any)
24The Struts Framework Controller Layer
- XML Configuration Document (/WEB-INF/struts-config
.xml) - Standard place to configure all aspects of the
application's behavior - DTD included for optional (but recommended)
validation - Logical-to-physical mappings for Actions,
ActionForms, and ActionForwards - General configuration settings
- Struts 1.1 Configuration Document per module if
more than one
25The Struts Framework Commons Libraries
- Non-Struts Specific Logic Factored Out
- commons-beanutils Generic bean property
manipulation - commons-collections Extensions to standard
Java2 collections classes - commons-dbcp Optional JDBC connection pool
- commons-digester XML parsing for configuration
files - commons-fileupload Support library for HTML
file uploads
26The Struts Framework Commons Libraries
- Non-Struts Specific Logic Factored Out
- commons-logging Application logging wrapper
- commons-pool Object pooling library
- commons-resources Message resources support
library - Commons-validator Field validation framework
27- Building Web Applications With Struts
28Building Web Applications With Struts
- Now that we understand the architecture of
Struts, let's look at parts of an example app
that is built with it - Struts includes a canonical example that is
useful in determining whether you have installed
things correctly - struts-example.war
- Application models (part of) an email portal site
that lets you maintain multiple subscriptions
29Sample Application Model Layer (Persistence
Tier)
- Modelled via a Data Access Object (DAO)
- org.apache.struts.webapp.example.UserDatabase
- public interface UserDatabase
- public User createUser(String username)
- public void close() throws Exception
- public User findUser(String username)
- public User findUsers()
- public void open() throws Exception
- public void removeUser(User user)
- public void save() throws Exception
30Sample Application Model Layer (Persistence
Tier)
- Default implementation based on loading an XML
document into memory - o.a.s.e.memory.MemoryUserDatabase
- JDBC-based (or LDAP-based) implementation is easy
to imagine, and would be transparent to the
business logic - Implementation selection implemented via a PlugIn
... see configuration file example later
31Sample Application Model Layer (Business Logic)
- Two common Struts design patterns illustrated
- View --gt View --gt Action
- Welcome Page has link to logon page
- lthtmllink page/logon.jspgt...lt/htmllinkgt
- Logon page instantiates LogonForm bean
- Form submit goes to /logon action
- View --gt Action --gt View --gt Action
- Setup action /editRegistration?actionEdit
pulls data from database and populates form
bean - Registration page /registration.jsp displays
current data - Form submit goes to /saveRegistration action
32Sample Application View Layer (logon.jsp)
- lt_at_ page contentTypetext/htmlcharsetUTF-8
gt - lt_at_ taglib uri/WEB-INF/struts-bean.tld
- prefixbean gt
- lt_at_ taglib uri/WEB-INF/struts-html.tld
- prefixhtml gt
- lthtmlhtml localetruegt
- ltheadgt
- lttitlegt
- ltbeanmessage keylogon.title/gt
- lt/titlegt
- lthtmlbase/gt
- lt/headgt
33Sample Application View Layer (logon.jsp)
- ltbody bgcolorwhitegt
- lthtmlerrors/gt
- lthtmlform action/logon focususername
- onsubmitreturn validateLogonForm(this)
gt - lttable border0 width100gt
- lttrgt
- ltth alignrightgt ltbeanmessage
keyprompt.username/gt - lt/thgt
- lttd alignleftgt
- lthtmltext propertyusername size16/gt
- lt/tdgt
- lt/trgt
34Sample Application View Layer (logon.jsp)
- lttrgt
- ltth alignrightgt ltbeanmessage
keyprompt.password/gt - lt/thgt
- lttd alignleftgt
- lthtmlpassword propertypassword
- size16/gt
- lt/tdgt
- lt/trgt
- lt/tablegtlt/htmlformgt
- lthtmljavascript formNamelogonForm
- dynamicJavascripttrue
- staticJavascriptfalse/gt
- ltscript languageJavascript .../gt
- lt/bodygtlt/htmlhtmlgt
35Sample Application Controller Layer
- No application logic required Struts does
everything for you -) - Controller functionality is configured via
XML-based files - struts-config.xml Struts controller
configuration - validation.xml Validator framework
configuration - web.xml Web application configuration
36Sample Application Struts Configuration
(struts-config.xml)
- ltstruts-configgt
- ltform-beansgt
- ...
- ltform-bean namelogonForm
- typeorg.apache.struts.action.DynaActionForm
gt - ltform-property nameusername
- typejava.lang.String/gt
- ltform-property namepassword
- typejava.lang.String/gt
- lt/form-beangt
- ltform-bean nameregistrationForm
- typeorg.apache.webapp.example.RegistrationF
orm/gt - ...
- lt/form-beansgt
37Sample Application Struts Configuration
(struts-config.xml)
- ltglobal-forwardsgt
- ltforward namelogoff path/logoff.do/gt
- ltforward namelogon path/logon.do/gt
- ltforward nameregistration
- path/registration.jsp/gt
- ltforward namesuccess
- path/mainMenu.jsp/gt
- lt/global-forwardsgt
38Sample Application Struts Configuration
(struts-config.xml)
- ltaction-mappingsgt
- ltaction path/editRegistration
- typeorg.apache.struts.webapp.example.EditRegi
strationAction - nameregistrationForm
- scoperequest validatefalsegt
- ltforward namesuccess
- path/registration.jsp/gt
- lt/actiongt
- ltaction path/saveRegistration
- typeorg.apache.struts.webapp.example.SaveRegi
strationAction - nameregistrationForm
- scoperequest validatetrue
- inputregistration/gt
39Sample Application Struts Configuration
(struts-config.xml)
- ltaction path/logon
- typeorg.apache.struts.webapp.example.
LogonAction - inputrequest
- namelogonForm
- scoperequest/gt
- ...
- lt/action-mappingsgt
- ltcontrollergt
- ltset-property propertyinputForward
- valuetrue/gt
- lt/controllergt
- ltmessage-resources
- parameterorg.apache.struts.example.Application
Resources/gt
40Sample Application Struts Configuration
(struts-config.xml)
- ltplug-in classNameorg.apache.struts.webapp.ex
ample.memory.MemoryDatabasePlugIngt - ltset-property propertypathname
- value/WEB-INF/database.xml/gt
- lt/plug-ingt
- ltplug-in classNameorg.apache.struts.validator.
ValidatorPlugIngt - ltset-property propertypathnames
- value/WEB-INF/validator-rules.xml,
- /WEB-INF/validation.xml/gt
- lt/plug-ingt
- lt/struts-configgt
41Sample Application Struts Configuration
(validation.xml)
- ltform-validationgt
- ltformsetgt
- ltform namelogonFormgt
- ltfield propertyusername
- dependsminlength,...gt
- ltarg0 keyprompt.username/gt
- ltarg1 keyvarminlength
- nameminlength
- resourcefalse/gt
- ltvargtltvar-namegtminlengthlt/var-namegt
- ltvar-valuegt3lt/var-valuegtlt/vargt
- ...
- lt/fieldgt
- ...
- lt/formgt
- ...
- lt/formsetgt
- lt/form-validationgt
42Sample Application Webapp Configuration
(web.xml)
- ltweb-appgt
- ltservletgt
- ltservlet-namegtControllerlt/servlet-namegt
- ltservlet-classgt
- org.apache.struts.action.ActionServlet
- lt/servlet-classgt
- ltinit-paramgt
- ltparam-namegtconfiglt/param-namegt
- ltparam-valuegt
- /WEB-INF/struts-config.xml
- lt/param-valuegt
- lt/init-paramgt
- ltload-on-startupgt 1 lt/load-on-startupgt
- lt/servletgt
43Sample Application Webapp Configuration
(web.xml)
- ltservlet-mappinggt
- ltservlet-namegtControllerlt/servlet-namegt
- lturl-patterngt .do lt/url-patterngt
- lt/servlet-mappinggt
- ...
- lt/web-appgt
44 45Struts 1.1 Release
- When? Real Soon Now
- What new features?
- Apache Commons Libraries
- DynaActionForm
- Declarative Exception Handling
- Nested Tag Library
- PlugIn API
- Sub-Application Module Support
- (Contributed) STRUTS-EL Tag Libraries
46Struts and JSTL
- JSP Standard Tag Library (JSTL) 1.0
- Expression language (customer.addressmailing
.city) - General purpose actions (out, set, remove, catch)
- Conditional actions (if, choose, when, otherwise)
- Iterator actions (forEach, forTokens)
- URL actions (import, url, redirect, param)
- Internationalization actions (message, setLocale,
bundle, setBundle, message, param,
requestEncoding) - Formatting actions (timeZone, setTimeZone,
formatNumber, parseNumber, formatDate, parseDate)
47Struts and JSTL
- JSP Standard Tag Library (JSTL) 1.0, continued
- SQL actions (not relevant in an MVC framework
environment) - XML core actions (parse, out, set)
- XML flow control actions (if, choose, when,
otherwise, forEach) - XML transform actions (transform, param)
- The struts-xxx-el libraries are a bridge for
Struts developers who want to leverage JSTL tags,
and expression language syntax, now
48Struts and JSF
- JavaServer Faces (currently under development in
JSR-127) - Goals
- Standard GUI component framework for web
applications - RenderKits for different rendering environments
(browser vs. wireless device, different locales,
etc.) - Struts will provide an integration library
- Requires changes to view layer and
struts-config.xml file only! - Plugs in to RequestProcessor APIs
49 50This Presentation Online
- StarOffice 6.0
- http//www.apache.org/craigmcc/apachecon-2002-str
uts.sxi - Powerpoint
- http//www.apache.org/craigmcc/apachecon-2002-str
uts.ppt
51Internet Technologies
- Hypertext Markup Language (HTML) 4.01
- http//www.w3.org/TR/html4/
- Hypertext Transfer Protocol (HTTP) 1.1
- http//www.ietf.org/rfc/rfc2616.txt
- Uniform Resource Identifiers (URI)
- http//www.ietf.org/rfc/rfc2396.txt
52Model Layer Standard Java APIs
- JavaBeans
- http//java.sun.com/products/javabeans/
- Java Database Connectivity (JDBC)
- http//java.sun.com/products/jdbc/
- Java Data Objects
- http//java.sun.com/products/jdo/
- http//jcp.org/jsr/detail/12.jsp
- Java Naming and Directory Interface
- http//java.sun.com/products/jndi/
- Enterprise JavaBeans (EJB)
- http//java.sun.com/products/ejb/
53Model Layer Persistence Frameworks
- Castor
- http//castor.exolab.org/
- Java Data Objects
- http//java.sun.com/products/jdo/
- Object/Relational Bridge
- http//jakarta.apache.org/ojb/
- Torque
- http//jakarta.apache.org/turbine/torque/
54View Layer Standard Java APIs
- Servlets
- http//java.sun.com/products/servlet/
- JavaServer Pages (JSP)
- http//java.sun.com/products/jsp/
- JSP Standard Tag Library (JSTL)
- http//java.sun.com/products/jsp/jstl/
- JavaServer Faces
- http//java.sun.com/j2ee/javaserverfaces/
- http//jcp.org/jsr/detail/127.jsp
55Struts Resources
- The Struts and Commons Web Sites
- http//jakarta.apache.org/struts/
- http//jakarta.apache.org/commons/
- Recent Books About Struts
- Cavaness, Chuck Programming Jakarta Struts
O'Reilly - Goodwill, James Mastering Jakarta Struts John
Wiley - Husted, Ted Java Web Development With Struts
Manning - Spielman, Sue The Struts Framework Practical
Guide for Programmers Morgan Kaufman - Turner, James Struts Kick Start Sams
56Design Patterns Resources
- The Java Blueprints Web Site
- http//java.sun.com/blueprints/
- Design Patterns Books
- Gamma, Erich (et. al.) Design Patterns Elements
of Reusable Object-Oriented Software
Addison-Wesley - Alur, Deepak (et. al.) Core J2EE Patterns Best
Practices and Design Strategies Prentice Hall
57