Académique Documents
Professionnel Documents
Culture Documents
Session Outline
Web Applications Backgrounder The Model-View-Controller Architecture The Struts Framework Building A Web Application With Struts Resources
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
For relatively simple applications, a simple architecture works fine For each page in the user interface ...
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
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
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)
Should manage permanent storage of application data Typically shared across many applications API should expose data retrieval and storage operations (while hiding the mechanisms)
Typically in HTML or an XML-based dialect Normally a combination of static and dynamic content Device or browser type User preferences / personalization Internationalization and localization requirements Accessibility requirements
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.
Action acquires information from persistence tier Exposes information as request/session attributes View layer pulls data from attributes for display
ActionForm Standard JavaBean design pattern DynaActionForm Property names and types defined in Struts configuration file
reset() -- Reset form properties to initial state validate() -- Perform field-level validations
Allows redisplay of invalid input
Locale Standard Java class representing a choice of language and/or country MessageFormat Standard Java class representing an individual message with replaceable parameters:
MessageResources Struts abstraction around sets of messages for supported locales ActionErrors / ActionMessages Struts collections of localized messages
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
struts-nested.tld -- Nested variants of standard tags that resolve relative references against beans struts-tiles.tld Full features layout management library
struts-xxx-el.tld Versions of standard Struts tag libraries that support the expression language syntax of JSP Standard Tag Library
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
ActionServlet Standard implementation of controller At application startup, reads configuration file and initializes resources
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
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
execute() -- Invoked for each request Can (but typically does not) create response content directly Typically returns ActionForward to select resource to prepare response
processLocale() -- Record user's locale preference (if not already present) processPreprocess() -- general purpose preprocessing hook processMapping() -- select Action to be utilized processRoles() -- perform security role-based restrictions on action execution processActionForm() -- Create or acquire an appropriate ActionForm instance
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)
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
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
commons-logging Application logging wrapper commons-pool Object pooling library commons-resources Message resources support library Commons-validator Field validation framework
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
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; }
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
Two common Struts design patterns illustrated View --> View --> Action
<html:link page=/logon.jsp>...</html:link>
Logon page instantiates LogonForm bean Form submit goes to /logon action
Setup action /editRegistration?action=Edit pulls data from database and populates form bean Registration page /registration.jsp displays current data Form submit goes to /saveRegistration action
<%@ taglib uri=/WEB-INF/struts-bean.tld prefix=bean %> <%@ taglib uri=/WEB-INF/struts-html.tld prefix=html %> <html:html locale=true> <head> <title> <bean:message key=logon.title/> </title> <html:base/> </head>
No application logic required Struts does everything for you :-) Controller functionality is configured via XMLbased files:
struts-config.xml Struts controller configuration validation.xml Validator framework configuration web.xml Web application configuration
Current Events
Apache Commons Libraries DynaActionForm Declarative Exception Handling Nested Tag Library PlugIn API Sub-Application Module Support (Contributed) STRUTS-EL Tag Libraries
Expression language (${customer.address[mailing].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)
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
Standard GUI component framework for web applications RenderKits for different rendering environments (browser vs. wireless device, different locales, etc.)
Requires changes to view layer and strutsconfig.xml file only! Plugs in to RequestProcessor APIs
Resources
StarOffice 6.0:
http://www.apache.org/~craigmcc/apachecon-2002-struts.sxi http://www.apache.org/~craigmcc/apachecon-2002-struts.ppt
Powerpoint:
Internet Technologies
JavaBeans:
Castor:
http://jakarta.apache.org/turbine/torque/
Servlets:
JavaServer Pages (JSP): JSP Standard Tag Library (JSTL): JavaServer Faces:
http://java.sun.com/j2ee/javaserverfaces/ http://jcp.org/jsr/detail/127.jsp
Struts Resources
http://jakarta.apache.org/struts/ http://jakarta.apache.org/commons/ 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
http://java.sun.com/blueprints/ Gamma, Erich (et. al.); Design Patterns: Elements of Reusable Object-Oriented Software; AddisonWesley Alur, Deepak (et. al.); Core J2EE Patterns: Best Practices and Design Strategies; Prentice Hall
Q&A