Power of Frameworks
Frameworks:
Provides abstraction of a particular concept Defines how these abstractions work together to solve a problem Framework components are reusable Organizes patterns at higher level Provides generic behaviour (many different applications can be built with the use of the same application)
Web Browser
JSP
JavaBean
MVC Pattern
Change notification Model Query state Change state
User input
View View selection events Controller
JavaBean
Struts
Framework for building Web applications using Java Builds on MVC pattern Located at: http://jakarta.apache.org/struts/
Struts History
Created in 2000 by Craig R. McClanahan Donated to ASF in 2000 Current stable release: 1.3.5 Soon (2006) to be released 2.0 1.x will be around - there is new development, great community, many applications are developed in 1.x
Struts MVC
Struts does not specify how to implement Model part of MVC JSP and Struts Tag Libraries used for View part of MVC Struts Controller implemented as: ActionServlet and ActionMapping
Struts MVC
3 Major Components
Servlet controller (Controller) Java Server Pages (View) Application Business Logic (Model)
Controller bundles and routes HTTP request to other objects in framework (Actions) Controller parses configuration file
Struts MVC
Configuration file contains action mappings (determines navigation) Controller uses mappings to turn HTTP requests into application actions Mapping must specify
A request path Object type to act upon the request
View Components
HTML DTO Struts ActionForms objects JavaServer Pages Struts Tags Custom Tags Java Resource Bundles Other: graphics, downloads, etc.
Controller Components
org.apache.struts.ActionServlet is a main component of Struts org.apache.struts.action.Action extension of controller component (defined in action mapping in the configuration file)
Controller Components
Deployment descriptor for Struts
This file provides for a configuration of controller components (actions), resources, model components: JavaBeans and other resources
Controller Components
The action mapping example <action-mappings> Action mapping name <action path="/addBookAction type= "edu.depaul.struts_example.BookInputAction" name="addBookBean" mapping type scope="request" input="/add_book.jsp"> Form Bean name <forward name="Go" path="/result.jsp"/> <forward name="cancel" forward definition path="/index.html"/> </action>
Model Components
System State Beans A set of one or more JavaBeans classes, whose properties define the current state of the system Example: shopping cart In a J2EE application a model is usually encapsulated as a layer of Session Faades
Override: Provide JavaBeans/style properties that match an HTML form input/output values
Struts Actions
For every action in the application , a custom Action is defined These a similar to servlets Short lived (for the duration of the request) Stateless do not put any state in the Action classes
Struts Action
FQCN: org.apache.struts.action.Action Implementations subclass this class and provide implementation of execute method:
ActionForward execute(ActionMapping , ActionForm , HttpServletRequest , HttpServletResponse );
Action.execute() Arguments
ActionMapping - provides access to the information stored in the configuration file (struts-config.xml) entry that configures this Action class. ActionForm formThis is the form bean. By this time, the form bean has been pre-populated and the validate() method has been called and returned with no errors (assuming that validation is turned on). All the data entered by the user is available through the form bean. HttpServletRequest requestThis is the standard JSP or Servlet request object. HttpServletResponse responseThis is the standard JSP or Servlet response object.
03StrutsSimple Demo
Web Container
Browser 1 ActionServlet 5 JSP View
struts-config
Request Processing
If action mapping defined in the configuration file, the Controller Servlet/RequestProcessor will perform the following:
Check session or request for instance of bean of appropriate class If no session/request bean exists, one is created automatically For every request parameter whose name corresponds to the name of a property in the bean, the corresponding setter method will be called The validate() method of ActionForm is called The updated ActionForm bean will be passed to the Action Class execute() method when it is called, making these values immediately available The execute() method must return an instance of ActionForward instructing the controller which is the next view (page) The next page is merged with data passed in request or session object, and then renders HTML
Request Processing
4 ActionForm 3 1 Web Browser displays page 2 Controller Model Action 5
struts-config
JSP Page
Form Construction
The Basics of Form Processing This section provides information on the following tags: <html:form> - Render an HTML <form> element <html:text> - Text box INPUT element <html:hidden> INPUT type=hidden element <html:submit>Place a Submit INPUT element <html:cancel>Place a Submit INPUT element which can be used to cancel workflow
</html:select> Where address is a form bean property which will be set with a selected value addresses Collection type property for inputs
Input Validation
Validation can be provided:
FormBean.validate(ActionMapping mapping, HttpServletRequest request) Directly in the Action.execute() method:
ActionMessages actionMessages = new ActionMessages(); if (simpleForm.getFirstName() == null ||simpleForm.getFirstName().equals("")) { actionMessages.add("firstName", new ActionMessage("field.required")); }
Input Validation
if (!actionErrors.isEmpty()) { saveMessages(request, actionErrors); return actionMapping.getInputForward(); } getInputForward(); -> sends back name of a page from which the Action was invoked
Strings in ActionForm
Struts converts data according to property data type If typed value cannot be converted to appropriate type, then exception is thrown Exception cannot be intercepted happens before validation Best practice: all properties are Strings
Message Configuration
Resource Bundle specified in a struts-config file: <message-resources parameter="strutsexamples" /> Simple Java properties file: message_key=Message Text Easy to do I18N
Message Output
<html:errors> - outputs all error messages <html:errors property=propName> outputs a message for property propName if one exists
Global Messages
Page Global Messages: Adding: messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(this.message.key) ); Displaying: <html:messages property= org.apache.struts.action.GLOBAL_MESSAGE/>
Bean Tags
The <bean:cookie> tag retrieves a cookie or cookies sent to the server from thebrowser. The <bean:header> Tag - provides access to the HTTP header The <bean:parameter> tag enables you to explicitly get a parameter passed into this page (either by a form submit or by arguments in the URL). The <bean:page> Tag: to gain access to the request, session, response, Struts config, or application data. The id attribute must be one of the strings request, session, config, response, or application).
<bean:header id=lang name=Accept-Language/> The preferred language for this browser is: <bean:write name=lang/>
<bean:parameter id="bean1" name="bean1" /> <bean:write name=bean1 property=name/> <bean:page id=this_session property=session/> Session Created = <bean:write name=this_session property=creationTime/>
DynaActoinForms
org.apache.struts.action.DynaActionForm
config: <form-bean name=userForm type=org.apache.struts.action.DynaActionForm> <form-property name=userId type=java.lang.String initial=admin/> <form-property name=password type=java.lang.String/> </form-bean> No need to write any Java. Validation? There is no validate() method. Solution1: validate in Action Solution 2: sub-class the DynaActionForm class and add a validate() method Solution 3: Use validation framework Disadvantage: not type safe, typos can lead to hours of debugging (no Compile time type checking)
Validation Framework
Jakarta Commons Validator Framework
http://jakarta.apache.org/commons
Deployed as a Struts Plugin Extended by Struts to provide generic validation rules Common Rules:
check for required fields check for max/min size check for the right data type
Validator Setup
<plug-in className="org.apache.struts.validator.ValidatorPlugIn"> <set-property property="pathnames" value="/org/apache/struts/validator/validator-rules.xml, /WEBINF/validation.xml"/> <set-property property="stopOnFirstError" value="true"/> </plug-in>
Validator Files
validation-rules.xml contains all possible rules validation.xml contains mappings of forms, properties and rules
Validator Example
DynaValidatorForm
Configure a dyna-form in struts-config.xml file <form-bean name="userForm"
type="org.apache.struts.validator.DynaValidatorForm">
<form-property name="userId" type="java.lang.String"/> <form-property name="password" type="java.lang.String"/> </form-bean> DynaValidatorForm - provides basic field validation based on an XML file
Password <html:password property="password"/> <html:errors property="password"/> <html:submit value="Submit"/> <html:cancel value="Cancel"/> </html:form>
In this case, the error message returned by the framework in case this field does not pass validation would be: User Id exceeded maximum length.
Validator Framework
mixing programmatic invocation and XML rules
Validator Framework
Struts bakes rules directly into Jakarta Validator Framework. Jakarta Framework allows for any method signature, but Struts requires exact signature dependency in Struts- difficult to reuse validators in a different environment JavaScript can break if user disables JS in client Better to implement validation logic in a framework independent manner (even if using Jakarta Validator) and invoke validations from validate() methods this will lead to more infrastructure work
Struts-Tiles
Tool for creating reusable layouts for sites Open Source Project (ASF) Integrated with Struts Not Enabled by default Allows for tiles definitions in XML
Struts-Tiles
Need to define a Tiles plugin in strutsconfig.xml:
<plug-in className= "org.apache.struts.tiles.TilesPlugin"> <set-property property="definitions-config" value="/WEB-INF/tiles-defs.xml" /> </plug-in>
Close to the end of file with all other plugins
Struts-Tiles
Create template JSP(template.jsp): <table border="1"> <tr> <td> <tiles:insert attribute='header'/> </td></tr> <tr> <td> <tiles:insert attribute='menu'/> </td></tr> <tr> <td> <tiles:insert attribute='content'/> </td></tr> <tr> <td> <tiles:insert attribute='footer'/> </td></tr> </table>
Struts-Tiles
Provide Tiles Definitions in the tiles-defs.xml file:
<definition name=".baseDef" page="/tiles/template.jsp"> <put name="title" value="Base Template Page"/> <put name="header" value="/tiles/header.jsp"/> <put name="footer" value="/tiles/footer.jsp"/> <put name="menu" value="/tiles/menu.jsp"/> <put name="content" value="/tiles/blank.jsp"/> </definition>
Struts-Tiles
<definition name=".index" extends=".baseDef"> <put name="title" value="New Page Title"/> <put name="content" value="/tiles/index.jsp"/> </definition> This definition extends .baseDef and overrides title and content fields
Struts-Tiles
Provide Action Mapping in the <action path="/someAction" ...
... </action>
Struts 2.0
Bottom Line: Integrated with WebWork Breaks backwards compatibility 1.x is deeply entrenched in enterprise JSF is gaining momentum Struts 1.x has been too long in the 1.x mode Is there future for 2.0? - time will tell