Strutsjspservlet

  • 754 views
Uploaded on

 

More in: Education , Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
754
On Slideshare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
43
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide
  • Struts and Tiles Tutorial -
  • Struts and Tiles Tutorial - This provides the base for a model view controller architecture.
  • The <set-property> tag is the only tag under the data-source node. Acceptable attributes of set-property: property value id
  • Tags under the form-beans node. Form-bean name type className dynamic id Allowable tags under form-bean with their attributes Description Display-name Form-property name type className initial size Icon Set-property property value id
  • Tags under the global-exceptions node Exception type key bundle className handler id path scope Tags under Exception Description Display-name Icon Set-property property value id
  • Tags under the global-forwards node Forward name path className contextRelative id redirect Tags under the forward node Description display=-name Icon set-property property value id
  • Action is the only tag under the action-mapping node it have the following attributes: Name Input Path Scope Type Attribute className Forward Id Include Parameter Prefix Roles Suffix Unknown Validate Tags under the action node Description Display-name Exception Forward Icon Set-property
  • The Controller tag has several attributes associated with it: processorClass bufferSize className contentType Debug forwardPattern Id inputForward Locale maxFileSize memFileSize multipartClass Nocache pagePattern tempDir Tags that can be used under the controller node Set-property
  • The Message-resources tag has several attributes associated with it: parameter className Factory id Key Null Tags that can be used under the message-resources node Set-property
  • The plug-in tag has a couple of attributes associated with it: className Id Tags that can be used under the plug-in node Set-property
  • The paramName does not need to be specified if the nested:link is used. It must be used nested in a form or in an iterator tag.
  • The value of isUSCitizen must be set to false in the reset() method for this control to work correctly. This is based on how checkbox values are sent in html.
  • It may be useful to create another validation-rules-<company>.xml for your company specific validation rules.
  • Unless you are developing your own validation rules, you should even need to look at this file. We are looking at it in an effort to provide a greater understanding of how the framework works.
  • The resource = false, tells the framework to not lookup anything from the resource file, to use the key as the name The ${var:minlength} is replaced with the value of var->var-name== minlength which in this case is 5. This allows the configuration of the value once.
  • How could you create a error message which would display the configured datePattern that is required?
  • Example: <plug-in className="org.apache.struts.tiles.TilesPlugin"> <set-property property="definitions-config" value="/WEB-INF/tiles-defs.xml" /> <set-property property="definitions-debug" value="1"/> <set-property property="definitions-parser-details" value="0"/> <set-property property="definitions-parser-validate" value="true"/> <set-property property="definitions-factory-class" value="com.codementor.TilesFactory"/> </plug-in>
  • <definition extends="main" name="failure.page"> <put name="body" value="/Failure.jsp" /> <put name="title" value="Failure Page" /> </definition> </tiles-definitions>
  • <plug-in className="org.apache.struts.tiles.TilesPlugin"> <set-property property="definitions-config" value="/WEB-INF/tiles-defs.xml" /> </plug-in> </struts-config>

Transcript

  • 1. 3004 Java Web Development with Struts and Tiles Ken Sipe Chief Instructor / TO Code Mentor
  • 2. Presentation Goal
    • Provide enough understanding for someone new to start leveraging Struts.
    • Dig deep with several nuggets tips for attendees well versed in Struts.
  • 3. Presentation Agenda
    • Struts Intro
    • Struts Fundamentals
    • Struts Tags / Working with Forms
    • Struts Validation
    • Tiles
  • 4. About the Speaker
    • Sun Certified Java 2 Architect.
    • Instructor for VisiBroker for Java, OOAD, Rational Rose, and Java Development.
    • Frequently speaks on the subject of distributed computing programming, including CORBA and EJB architecture.
    • JBoss Certified Developer ;)
  • 5. Understanding the JSP Models With a Quick Look at Java Web Apps
  • 6. Java 2 Web Applications
    • Java 2 web application options:
      • Servlets
        • + Great for Java people
        • - Difficult to manage graphical changes in HTML layout.
      • JSP
        • + Great for web developers
        • - Seductive tendency to write logic in the JSP page.
  • 7. JSP Model 1
    • Web applications where JSP pages are used for every aspect of the development.
    Option 2 Option 1
  • 8. JSP Model 1 Observation
    • The Good
      • Easiest Solution
    • The Bad
      • Presentation and Logic are mixed.
    • The Ugly
      • No reuse possibilities
    JSP2 JSP1 JSP3 JSP4 Presentation Presentation Present. Ctrl Presentation Logic Present. Ctrl Logic Logic
  • 9. JSP Model 2
    • Web applications where JSP pages are used for the GUI aspect of the web development and the logic of the application is placed in the servlets it posts to.
  • 10. Model 2
    • The Good
      • Reuse opportunities
        • Other application may be able to use the same code.
    • The Bad
      • There is no longer a one to one mapping from a view to a single source of code.
    • The Ugly
      • Takes more forethought.
    JSP2 JSP1 JSP3 Logic Control
  • 11. Introduction MVC
  • 12. What Is a MVC?
    • MVC stands for model / view / controller.
      • A software pattern where logic is separated from the model and view in order to provide for better reuse possibilities.
      • A software pattern recognized in the early days of small talk.
      • Documented in the GoF book.
  • 13. Web Application MVC Pattern
    • Model
      • Information is provided in objects or beans
    • View
      • The JSP provide the view
    • Controller
      • Servlet provides control logic and becomes the controller
    Controller (Servlet) Model (Beans) View (JSPs) View (JSPs) View (JSPs) View (JSPs) View (JSP) 1 2 3 4 5
  • 14. MVC Collaboration Diagram
  • 15. Struts As a MVC Framework We Can Rebuild It. We Have the Technology. Better… Stronger… Faster...
  • 16. What Are Struts?
    • Apache’s open source web application model view controller framework project!
    • Takes MVC to the next level for web applications.
  • 17. Struts Collaboration Diagram
  • 18. ActionServlet
    • <web-app>
    • <servlet>
    • <servlet-name>action</servlet-name>
    • <servlet-class> org.apache.struts.action.ActionServlet
    • </servlet-class>
    • <init-param>
    • <param-name>debug</param-name>
    • <param-value>2</param-value>
    • </init-param>
    • <init-param>
    • <param-name>config</param-name>
    • <param-value>/WEB-INF/struts-config.xml
    • </param-value>
    • </servlet>
    • <servlet-mapping>
    • <servlet-name>action</servlet-name>
    • <url-pattern>*.do</url-pattern>
    • </servlet-mapping>
    • ActionServlet is provided by the framework.
    • The Servlet must be mapped in the web.xml file.
      • Must have configuration file mapped
    • Lastly, Map the *.do URI to the Action Servlet
  • 19. strut-config.xml
    • <struts-config>
    • <!-- ========== Data Source Configuration === -->
    • <!-- ========== Form Bean Definitions === -->
    • <form-beans>
    • <form-bean name=&quot;LogonForm&quot;
    • type=&quot;com.codementor.LogonForm&quot;/>
    • </form-beans>
    • <!-- ========== Global Forward Definitions === -->
    • <global-forwards> </global-forwards>
    • <!-- ========== Action Mapping Definitions === -->
    • <action-mappings>
    • <action path=&quot;/logon&quot;
    • type=&quot;com.codementor.LogonAction&quot;
    • name=&quot;LogonForm&quot;
    • scope=&quot;request&quot;
    • input=&quot;/logon.jsp&quot;>
    • <forward name=&quot;success&quot; path=&quot;/sucess.jsp&quot;/>
    • <forward name=&quot;failure&quot; path=&quot;/failure.jsp&quot;/>
    • </action>
    • </action-mappings>
    • </struts-config>
    • XML configuration file
    • Allows for:
      • DataSource definition
      • Logical name definitions for Forms
      • View mappings
        • Local
        • Global
  • 20. Strut-config.xml For requests that hit URL=“/logon” The frame work will invoke execute() on an instance of class com.codementor.LogonAction Store request parameters in form variable “LogonForm” which is defined in another location in the xml document. If the logical name returned by perform() is “failure” go to page “/failure.jsp” If the Logical name returned by perform() is “success” go to “/success.jsp” <action path=&quot; /logon “ type= “ com.codementor.LogonAction ” name=&quot; LogonForm &quot; <forward name=&quot; failure &quot; path=&quot; /failure.jsp &quot; /> <forward name=&quot; success &quot; path=&quot; /success.jsp &quot; /> </action>
  • 21. Action Bean
    • import org.apache.struts.action.*;
    • public class LogonAction extends Action {
    • public ActionForward execute(
    • ActionMapping mapping,
    • ActionForm form,
    • HttpServletRequest request,
    • HttpServletResponse response)
    • throws IOException, ServletException
    • {
    • LogonForm theForm = (LogonForm)form;
    • String forward=&quot;failure&quot;;
    • if(theForm.getUserName().equals(&quot;borcon&quot;))
    • {
    • forward=&quot;success&quot;;
    • }
    • return mapping.findForward(forward);
    • }
    • }
    Action class’s perform is invoked by Action Servlet
  • 22. Action Form
    • import org.apache.struts.action.ActionForm;
    • public class LogonForm extends ActionForm {
    • private String userName;
    • private String password;
    • public String getUserName() {
    • return userName;
    • }
    • public void setUserName(String userName) {
    • this.userName = userName;
    • }
    • public void setPassword(String password) {
    • this.password = password;
    • }
    • public String getPassword() {
    • return password;
    • }
    • }
    • Action Form has properties which map to the HTML page.
    • Additionally the form can:
      • Reset
      • Validate
  • 23. Strut Powered JSP
    • <html:html locale=&quot;true&quot;>
    • <head>
    • <title>Logon Form</title>
    • <html:base/>
    • </head>
    • <body bgcolor=&quot;white&quot;>
    • <html:errors/>
    • <html:form action=&quot;logon&quot; focus=&quot;userName&quot;>
    • User Name: <html:text property=&quot;userName&quot; size=&quot;16&quot; maxlength=&quot;16&quot;/>
    • password: <html:password property=&quot;password&quot; size=&quot;16&quot; maxlength=&quot;16&quot;
    • <html:submit property=&quot;submit&quot; value=&quot;Submit&quot;/>
    • <html:reset/>
    • </html:form>
    • </body>
    • </html:html>
  • 24. Creating Your First Struts Application
  • 25. Struts Installation
    • Downlad the zip
      • http://apache.mirrors.hoobly.com/jakarta/struts/binaries/jakarta-struts-1.1.zip
      • Unzip and go!
      • There isn’t an “install”, however there are several files you’ll need.
      • Readme.txt has details
    • Main Files of interest
      • *.jar , especially struts.jar
      • *.tld
      • struts-blank.war
  • 26. Steps to Building
    • Step 1: Build your JSP in HTML format
      • It’s back to editing code
    • Step 2: Convert to Struts format
    • Step 3: Write the matching ActionForm
      • public class LogonForm extends ActionForm {}
    • Step 4: Write the Action class
      • public class LogonAction extends Action {}
  • 27. Steps to Building
    • Step 5: Register the entries in struts-config.xml
      • <action path=&quot;/logon&quot;
      • type=&quot;com.codementor.struts.LogonAction&quot;
      • name=&quot;logonForm&quot;
      • input=&quot;/Logon.jsp&quot; >
      • <forward name=&quot;success&quot; path=&quot;/Success.jsp&quot; />
      • <forward name=&quot;failure&quot; path=&quot;/Failure.jsp&quot; />
      • </action>
    • Step 6: Configure web.xml with the ActionServlet
  • 28. JSP Pages
    • Three Pages
      • Login Page
      • Success Page
      • Failure Page
  • 29. Logon Page – HTML Version
    • <html>
    • <head>
    • <title>Login Form</title>
    • </head>
    • <body bgcolor=&quot;#ffffff&quot;>
    • <form action=&quot;logon.do&quot;>
    • User Name: <input type=&quot;text&quot; name=&quot;userName&quot; size=&quot;16&quot; maxlength=&quot;16&quot;/><br />
    • Password: <input type=&quot;text&quot; name=&quot;password&quot; size=&quot;16&quot; maxlength=&quot;16&quot;/><br />
    • <input type=&quot;submit&quot; name=&quot;Submit&quot; value=&quot;Submit&quot;>
  • 30. Logon Page – Struts
    • <%@ taglib uri=&quot;/WEB-INF/struts-html.tld&quot; prefix=&quot;html&quot; %>
    • <html:html>
    • <head>
    • <title>Login Form</title>
    • </head>
    • <body bgcolor=&quot;#ffffff&quot;>
    • <html:form action=&quot;logon.do&quot; focus=&quot;userName&quot;>
    • <br>
    • User Name: <html:text maxlength=&quot;16&quot; property=&quot;userName&quot; size=&quot;16&quot;/><br />
    • Password: <html:text maxlength=&quot;16&quot; property=&quot;password&quot; size=&quot;16&quot;/><br />
    • <html:submit value=&quot;Submit&quot; property=&quot;Submit&quot;/>
    Added a cool feature
  • 31. Success and Failure Pages
    • Success.jsp
    • <html>
    • <head>
    • <title>
    • Success
    • </title>
    • </head>
    • <body bgcolor=&quot;#ffffff&quot;>
    • <h1>
    • Successful Login
    • </h1>
    • </body>
    • </html>
    • Failure.jsp
    • <html>
    • <head>
    • <title>
    • Failure
    • </title>
    • </head>
    • <body bgcolor=&quot;#ffffff&quot;>
    • <h1>
    • Failed Login
    • </h1>
    • </body>
    • </html>
  • 32. Create Form Bean Class
    • package com.codementor;
    • import org.apache.struts.action.ActionForm;
    • public class LogonForm extends ActionForm {
    • private String password;
    • private String userName;
    • public String getPassword() {
    • return password;
    • }
    • public void setPassword(String password) {
    • this.password = password;
    • }
    • public String getUserName() {
    • return userName;
    • }
    • public void setUserName(String userName) {
    • this.userName = userName;
    • }
    • }
  • 33. Form Bean Config
    • <struts-config>
    • <form-beans>
    • <form-bean name=&quot;logonForm&quot;
    • type=&quot;com.codementor.LogonForm&quot; />
    • </form-beans>
    • </struts-config>
  • 34. Action Class
    • package com.codementor;
    • import org.apache.struts.action.*;
    • import javax.servlet.http.*;
    • public class LogonAction extends Action {
    • public ActionForward execute(ActionMapping mapping,
    • ActionForm form,
    • HttpServletRequest request,
    • HttpServletResponse response) {
    • LogonForm logonForm = (LogonForm) form;
    • String forward = &quot;failure&quot;;
    • if(logonForm.getUserName().equals(&quot;mentor&quot;))
    • {
    • forward = &quot;success&quot;;
    • }
    • return mapping.findForward(forward);
    • }
    • }
  • 35. Action Class Config
    • <action-mappings>
    • <action path=&quot;/logon&quot;
    • type=&quot;com.codementor.LogonAction&quot;
    • name=&quot;logonForm&quot;
    • input=&quot;/Login.jsp&quot;
    • scope=&quot;request&quot; />
    • </action-mappings>
    • </struts-config>
  • 36. Map The Forwards
    • <action-mappings>
    • <action path=&quot;/logon&quot;
    • type=&quot;com.codementor.LogonAction&quot;
    • name=&quot;logonForm&quot;
    • input=&quot;/Login.jsp&quot;
    • scope=&quot;request&quot; >
    • <forward name=&quot;success&quot; path=&quot;/Success.jsp&quot; />
    • <forward name=&quot;failure&quot; path=&quot;/Failure.jsp&quot; />
    • </action>
    • </action-mappings>
    • </struts-config>
  • 37. Struts in web.xml
    • <web-app>
    • <servlet>
    • <servlet-name>action</servlet-name>
    • <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    • <init-param>
    • <param-name>config</param-name>
    • <param-value>/WEB-INF/struts-config.xml</param-value>
    • </init-param>
    • <init-param>
    • <param-name>debug</param-name>
    • <param-value>2</param-value>
    • </init-param>
    • <load-on-startup>2</load-on-startup>
    • </servlet>
    Sets the logging level for struts Loads ActionServlet on startup ** important if there is a JSP page which could be referenced from the Client **
  • 38. Web.xml URI Mapping
    • <servlet-mapping>
    • <servlet-name>action</servlet-name>
    • <url-pattern>*.do</url-pattern>
    • </servlet-mapping>
  • 39. Configure Tags
    • <taglib>
    • <taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
    • <taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
    • </taglib>
    • <taglib>
    • <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
    • <taglib-location>/WEB-INF/struts-html.tld</taglib-location>
    • </taglib>
    • </web-app>
  • 40. Configure WebApp
    • /sample
    • Logon.jsp
    • Success.jsp
    • Failure.jsp
    • /WEB-INF
    • web.xml
    • struts-config.xml
    • *.tld – all the struts tld files
    • /lib
    • *.jars - all the struts jars
    • /classes
    • LogonAction
    • LogonForm
  • 41. Run The WebApp
  • 42. Demo
  • 43. Summary
    • JSP / Servlet Models
    • MVC
    • Struts Basics
    • Creating a Struts Application
  • 44. Questions?
  • 45. Struts Fundamentals
  • 46. Section Agenda
    • Form Beans
    • Action Classes
    • Struts Configuration File
  • 47. Form Beans
  • 48. Form Bean Types
    • ActionForm
      • Sub-class to create a standard form
    • ValidatorActionForm
      • Sub-class in order to use the validator framework
    • DynaActionForm
      • Generic Form
      • Form is defined in xml
    • DynaValidatorActionForm
      • DynaAction form which can be used with the validator framework
  • 49. ActionForm Class
    • Basic Type
    • Follows Rules for JavaBean
      • Collection of properties
    • Methods
      • Reset()
      • Validate()
    public class LogonForm extends ActionForm {}
  • 50. FormBean Reset() Method
    • public void reset(ActionMapping mapping, HttpServletRequest request) { }
    • Provides way to reset the form bean between action requests
    • Not needed if the form bean is at the Request Scope (Session is the default)
    • Think of as the constructor or the init() of the bean.
  • 51. FormBean Validate() Method
    • public ActionErrors validate(ActionMapping mapping, HttpServletRequest request)
    • {
    • return null;
    • }
    struts-config.xml <action path=&quot;/logon&quot; type=&quot;com.codementor…&quot; name=&quot;logonForm&quot; input=&quot;/Login.jsp&quot; scope=&quot;request&quot; /> validate=&quot;true&quot; </action-mappings>
    • Used to provide validation
    • Only called if configured in the struts-config.xml file.
    • Called prior to the action class
    • Return null is the default, meaning no errors
  • 52. ValidatorActionForm
    • Supports the Validator Framework
    • Discussed in the Validation Section of the course
      • There is a lot of detail in working with the validator frame work.
    public class LogonForm extends ValidatorActionForm {
  • 53. DynaForms
    • A form without a Form
    • There is no Java class to create
    • The form is configured in the struts-config file.
    • Example LogonForm
    • <struts-config>
    • <form-beans>
    • <form-bean name=&quot;LoginForm&quot; type=&quot;org.apache.struts.action.DynaActionForm&quot; >
    • <form-property name=&quot;userName&quot; type=&quot;java.lang.String&quot; />
    • <form-property name=&quot;password&quot; type=&quot;java.lang.String&quot; />
    • </form-bean> </form-beans>
  • 54. Working with DyanForms
    • Handling DynaForms in an Action Class is a little different.
      • There are no strongly type properties.
      • Consider a HashMap where the configured name is the key
    • Example:
    • DynaActionForm form = (DynaActionForm)actionForm;
    • form.get(&quot;userName&quot;);
  • 55. DynaValidatorActionForm
    • Work the same as DynaActionForms
    • Provide ability to use the validator framework.
  • 56. Actions
  • 57. Action Types
    • Actions
    • DispatchActions
    • LookupDispatchActions
    • ForwordActions
    • TilesActions
  • 58. Action Characteristics
    • Typically have one method, the execute method.
      • Models after the command pattern
    • Dissimilar from a Servlet
      • Lacks the doGet / doPost characteristics
      • Requires a different design as compared to Servlets
        • May require an Action for setting up display and an Action for retrieving POSTs
        • May programmatically determine the action in the Action class
        • May use one of the DispatchActions
  • 59. Action Class
    • Super-class to all Actions
    • public class LogonAction extends Action {
    • Required method for Actions
    • public ActionForward execute(ActionMapping mapping,
    • ActionForm actionForm,
    • HttpServletRequest request,
    • HttpServletResponse response) throws Exception {
  • 60. Action Configuration
    • <action-mappings>
    • <action input=&quot;/Login.jsp&quot; name=&quot;logonForm&quot; path=&quot;/logon&quot; scope=&quot;request&quot; type=&quot;com.codementor.LogonAction&quot; >
    • <forward name=&quot;success&quot; path=&quot;/Success.jsp&quot; />
    • <forward name=&quot;failure&quot; path=&quot;/Failure.jsp&quot; />
    • </action>
    • </action-mappings>
  • 61. DispatchAction
    • Super-class for all Dispatch type actions
    • public class LogonAction extends DispatchAction {
    • Provides ability to have multiple functions per Action
      • It has an execute method, because it is an Action, but do NOT override it.
    • Create methods with arbitrary names with signature similar to the execute method
  • 62. DispatchAction
    • public ActionForward <method.name> (ActionMapping mapping,
    • ActionForm actionForm,
    • HttpServletRequest request,
    • HttpServletResponse response) throws Exception {
    • Must have a parameter type configured
      • Defined in the struts-config file, determines the “dispatched” method
  • 63. Example DispatchAction
    • Let’s change our LogonAction to be able to login and to sendPassword.
    • Methods defined in the LogonAction
    • public ActionForward login (ActionMapping mapping,
    • ActionForm actionForm,
    • HttpServletRequest request,
    • HttpServletResponse response) throws Exception {
    • public ActionForward sendPassword (ActionMapping mapping,
  • 64. DispatchAction Config
    • <action name=&quot;logonForm&quot; path=&quot;/logon&quot; input=&quot;/Login.jsp&quot; scope=&quot;request&quot; type=&quot;com.codementor.LogonAction&quot; parameter=&quot;action&quot; >
    • <forward name=&quot;success&quot; path=&quot;/Success.jsp&quot; />
    • <forward name=&quot;failure&quot; path=&quot;/Failure.jsp&quot; />
    • </action>
    • Invoking the dispatched method:
    • localhost:8080/sample/logon.do?action=login
    • localhost:8080/sample/logon.do?action=sendPassword
    Defines the parameter used to get the action The name “action” is arbitrary, could be anything
  • 65. When to use DispatchActions
    • Multiple cohesive actions
      • CRUD
    • Consolidation of the logical model
      • If you have multiple Actions:
        • With the same backend relationships
        • Working with the same page
        • Combination of these
  • 66. LookupDispatchAction
    • It is a DispatchAction and carries all it’s characteristics and configuration requirements.
    • DispatchAction exposes in the URI the method name of the action
    • localhost:8080/sample/logon.do?action=login
  • 67. LookupDispatchAction
    • LookupDispatchAction provides a configurable way to define logical name mappings to physical method names, which are not exposed to the public.
      • Requires no extra configuration in the struts-config
    • Required method to implement in the LookupDispatchAction
    • protected Map getKeyMethodMap() {
  • 68. LookupDispatchAction Ex.
    • Using the previous DispatchAction, it’s configuration and method names
    • protected Map getKeyMethodMap() {
    • Map map = new HashMap();
    • map.put(“login.button&quot;, “login&quot;);
    • map.put(“send.password.button&quot;, “sendPassword&quot;);
    • return map;
    • }
    • Property File:
    • login.button =Login
    • send.password.button =Send Password
    Maps to hashmap which maps to method to invoke This mapping occurs in the property file.
  • 69. Invoke LookupDispatch
    • http://localhost:8080/sample/login.do?action=Login
    • Internal to the framework the parameter is reverse mapped to the key. The key then is used to invoke the method.
  • 70. ForwardAction
    • Used to forward to another resource
      • Useful in Tiles examples
    • Two approaches, provide the same result
      • Define the predefined ForwardAction
      • <action path=&quot;/home&quot; type=&quot;org.apache.struts.actions.ForwardAction&quot; parameter=&quot;index.jsp&quot;/>
      • Short-Hand XML
      • <action path=&quot;/home&quot; forward=&quot;index.jsp&quot;/>
  • 71. TilesAction
    • Used to provide controller logical to tiles.
      • Explained in the Tiles Section of the course.
    • Has a slightly different execute signature
    • public ActionForward execute(ComponentContext context,
    • ActionMapping mapping,
    • ActionForm form,
    • HttpServletRequest request,
    • HttpServletResponse response)
    • throws Exception {
  • 72. Forwards
  • 73. Local Forwards
    • Refers to the forwards defined per action
    • <action-mappings>
    • <action input=&quot;/Login.jsp&quot; name=&quot;logonForm&quot; path=&quot;/logon&quot; scope=&quot;request&quot; type=&quot;com.codementor.LogonAction&quot; >
    • <forward name=&quot;success&quot; path=&quot;/Success.jsp&quot; />
    • <forward name=&quot;failure&quot; path=&quot;/Failure.jsp&quot; />
    • </action>
    • </action-mappings>
    • Name is a logical String
    • Path is a view element is
      • Relative Resource (such as Success.jsp)
      • Tiles definition
      • Can be any URL
  • 74. Global Forwards
    • Global Forwards are forwards which are declared in the global section of the struts-config file.
    • Reduces multiply declared local forwards
    • Great to use with the <html:link> tag (discussed later)
    • <struts-config>
    • <global-forwards>
    • <forward name=&quot;Home&quot; path=&quot;/viewHome.do&quot; />
    • <forward name=&quot;Logon&quot; path=&quot;/Logon.jsp&quot; />
    • </global-forwards>
  • 75. Forward to Actions
    • It is common to have a forward go to another action class.
    • <forward name=&quot;failure&quot; path= &quot;/failure.do&quot; />
  • 76. Forward Redirects
    • By default forwards are forwards and not redirects.
    • To redirect the client
    • <forward name=&quot;success&quot; path=&quot;/Success.jsp&quot; redirect=&quot;true“ />
  • 77. Struts Configuration File
  • 78. Struts Configuration File
    • Defines the configuration for the Struts Application Module
    • Configured in the web.xml file for the ActionServlet
    • By convention usually named struts-config.xml
    • This section will walk through all the XML elements in the struts configuration file.
  • 79. Struts-Config.xml
    • DataSources
    • FormBeans
    • Global Exceptions
    • Actions
    • Controller
    • Message Resources
    • PlugIns
  • 80. Data Sources
    • Don’t use it, but here’s how 
    • <data-sources>
    • <data-source>
    • <set-property property=&quot;driverClass“
    • value=&quot;org.postgresql.Driver&quot;/>
    • <set-property property=&quot;password“ value=&quot;mypassword&quot;/>
    • <set-property property=&quot;url“
    • value=&quot;jdbc:postgresql://host/mydatabase&quot;/>
    • <set-property property=&quot;user“ value=&quot;myusername&quot;/>
    • </data-source>
    • </data-sources>
  • 81. Form Beans
    • Location where are form beans are defined.
    • Provides a logical name mapped to either:
      • Physical ActionForm Class
      • DynaActionForm Class
    • DynaActionForms define there form beans structures.
    • <form-beans>
    • <form-bean name=&quot;logonForm&quot; type=&quot;com.codementor.LogonForm&quot; />
    • </form-beans>
  • 82. Global Exceptions
    • Struts defines a way to do declarative exception handling
      • Exceptions are mapped to forward paths
      • Can be in combination with exception keys.
    • Global exceptions are leverage if there isn’t a configured local exception handler.
    • <global-exceptions>
    • <exception
    • type=&quot;app.ExpiredPasswordException&quot;
    • path=&quot;/changePassword.jsp&quot;/>
    • </global-exceptions>
  • 83. Global Forwards
    • Location of forwards defined to be global.
    • Provides default forward.
    • <global-forwards>
    • <forward name=&quot;Home&quot; path=&quot;/viewHome.do&quot; />
    • <forward name=&quot;Logon&quot; path=&quot;/Logon.jsp&quot; />
    • </global-forwards>
  • 84. Action Mappings
    • Action mappings is where the actions are configured.
    • Maps the action to the form bean.
    • Provides local forwards.
    • <action name=&quot;logonForm&quot; path=&quot;/logon&quot; input=&quot;/Login.jsp&quot; scope=&quot;request&quot; type=&quot;com.codementor.LogonAction&quot; parameter=&quot;action&quot;>
    • <forward name=&quot;success&quot; path=&quot;/Success.jsp&quot; />
    • <forward name=&quot;failure&quot; path=&quot;/Failure.jsp&quot; />
    • </action>
  • 85. Controller
    • Configuration of the RequestProcessor for this struts application module.
    • Provides customization to requests.
    • Commonly used for Tiles.
    • <controller processorClass=&quot;org.apache.struts.tiles.TilesRequestProcessor&quot; />
  • 86. RequestProcessor
    • Provides access to preprocessing to all requests
      • No need to extend the ActionServlet
    • Provides hooks into
      • ActionCreate
      • ActionForm
      • ActionForward
      • Processing:
        • Exceptions
        • Forwards
        • Locale
        • Path
        • Populate
  • 87. Message Resources
    • Location to Configure application resources.
    • Used for Internationalization
    • <message-resources parameter=&quot;com.codementor.ApplicationResources&quot; />
  • 88. Plugins
    • Used to configure Plugins for the application
    • Plugins provide startup and shutdown functionality through
      • Init()
      • Destroy
    • Commonly used for Tiles and Validation Framework
    • <plug-in className=&quot;org.apache.struts.tiles.TilesPlugin&quot;>
    • <set-property property=&quot;definitions-config&quot; value=&quot;/WEB-INF/tiles-defs.xml&quot; />
    • </plug-in>
  • 89. Summary
    • Form Beans
    • Action Classes
    • Struts Configuration File
  • 90. Questions?
  • 91. Working Struts Tags
  • 92. Section Agenda
    • Common Tags
    • Working with Forms
    • Useful Struts Java Classes
  • 93. Common Tags
  • 94. Most Common Struts Tags
    • html:form
    • html:img
    • html:image
    • html:errors
    • html:link
    • html:multibox
    • html:radio
    • html:checkbox
    • html:text
    • html:select
    • html:options
    • bean:write
    • bean:define
    • logic:iterator
    • logic:match
    • logic:equal
    • logic:notEqual
    • Nested versions of all these tags
    • tiles:insert
    • tiles:put
  • 95. Common Non-Form Tags
    • Define
    • Links
    • Images
    • Write
    • Message
    • Iterator
    • Nested Tags
  • 96. Bean:Define
    • Use for:
      • Access to bean not in the scope of an html form
      • To provide clarity when working with multiple nested properties
      • To provide script variable for included JSP pages.
    • Does NOT create an instance of a bean
      • It provides access to a bean in scope
    • Don’t use to define a form bean to a new script variable name
  • 97. Bean:Define <bean:define id=“employeeList“ name=“selectEmployeesForm“ property=“employeeList“ type=&quot;java.util.Collection&quot;/> Defines a referenceable variable named employeeList which is assigned that value Of the property employeeList in the form Bean. Collection employeeList = selectEmployeesForm.getEmployeeList();
  • 98. Struts Links
    • Preferred order to provide a link in Struts
      • Forward
        • <html:link forward=“Home”>
        • Uses the defined global forwards from the struts configuration file.
      • Page
        • <html:link page=“/someAction.do”>
      • HREF
        • <html:link href=“”>
        • Required for javascript
        • <html:link href=“javascript:history.back(1)”>Back </html:link>
      • Action
        • <html:link action=“someAction”
  • 99. Links Example
    • Text Link
    • <html:link forward=“Home&quot;>Home Page</html:link>
    • Image Link
    • <html:link page=&quot;/viewReport.do&quot;>
    • <html:img src=&quot;/images/emp_button_view_report.gif&quot; />
    • </html:link>
  • 100. Parameterized Links
    • Links which depend on information available through the form bean
    • <html:link page=&quot;/viewReport.do&quot; paramId=&quot;model“ paramName=&quot;viewModelForm&quot; paramProperty=&quot;model&quot;>
    • <html:img src=&quot;/images/emp_button_view_report.gif&quot; />
    • </html:link>
  • 101. Parameterized Link
    • Will create a link on the image to: /viewReport.do?model=<%=viewModelForm.getModel() %>
    • Which may look like:
    • /viewReport.do?model=detail
  • 102. Images
    • There are 2 images tags
      • html:img
        • Used for normal images
        • Used with links
      • html:image
        • Used for images which function as submit buttons
        • Must be in an struts form
  • 103. <html:img>
    • <html:link page=&quot;/viewReport.do&quot;>
    • <html:img src=&quot;/images/emp_button_view_report.gif&quot; />
    • </html:link>
    • Or Simply
    • <html:img src=&quot;/images/emp_button_view_report.gif&quot; />
  • 104. <html:image>
    • <html:form action=“/action.do”>
    • <html:link src=&quot;/images/emp_button_view_report.gif&quot; />
    • </html:form>
  • 105. Bean:write
    • Used to retrieve a property from:
      • a form bean
      • a defined scripted variable (by bean:define)
      • <bean:write name=“modelForm” property=“clientName”/>
  • 106. Bean:Write JSP Equivalent: <%= modelForm.getClientName() %> If the named object is an object you do not have to define a property Ex: <bean:write name=“id” /> This commonly happens with a bean define or an id assigned in an iterator
  • 107. Displaying HTML on HTML
    • Struts will not display the source of html of an html page by default
    • Use the bean:write with the filter set to false.
  • 108. Bean:message
    • Used to retrieve a property from a configured property file.
    • We’ll look at this in detail in the Internationalization section.
      • <bean:message key=“ user.message”/>
  • 109. Bean:message
    • Can be used in combination with a bean (such as a form bean)
      • In this case the property clientInfo, of the modelForm bean has the key to the resource bundle.
      • The value of clientInfo is NOT displayed
      • It is used to lookup the value in the resource bundle which is displayed.
      • <bean:write name=“modelForm” property=“clientInfo”/>
  • 110. Logic:iterate
    • Used to iterate
      • An array
      • A Collection
    • All tags between the <logic:iterate> open and close tag will execute for each element.
  • 111. Logic:iterate Example
    • This would go through all the employees of the employeesForm
    • The employeesForm is the string from the struts config for the form bean that is assigned to the action that forwarded to this JSP.
    • In a few slides we’ll evolve this example to something useful.
    • <logic:iterate id=“employeesForm&quot; property=“employees&quot;>
    • </logic:iterate>
  • 112. Nested Tags
    • Most of the tags have a nested version.
      • Usually reducing the required attributes for the extended tag.
    • Use Often!!!
    • Great for working through an iterator
    • Great for removing form bean dependencies in the JSP page.
  • 113. Nested Tags Example
      • Without nested in a form
      • <bean:write name=“modelSummaryForm” property=“clientName”/>
      • With nested
      • <nested:write property=“clientName”/>
      • It assumes the form bean! (When in a form tag)
  • 114. Nested Iterators
    • Revisit the Iterator Example:
      • This time the form bean is assumed
      • Also works great for writing the employees to the screen.
      • Assume we have an Employee Class with a FullName property in a Collection which is returned from the getEmployees() method of the form bean
    • <nested:iterate property=“employees&quot;>
    • <nested:write property=“fullName” />
    • <br/>
    • </nested:iterate>
  • 115. Working with HTML / Forms
  • 116. Working with Struts Forms
    • Struts Forms
    • Submit Buttons
    • Text Input
    • Combo Boxes
    • Radio
    • Checkbox
    • Multi-Box
    • Tables
    • Advance Forms
      • Dispatch Options
      • Javascripted submits
  • 117. Struts Forms
    • <html:form> creates a <form> tag in html.
    • It is a required tag for many of the struts tags
      • Specifically tags which are used with forms
        • Text
        • Dropdowns
      • JSP pages will NOT compile if these tags are used outside a form tag.
    • Example:
      • In this case there is special attribute named focuswhich creates javascript for the client.
        • On load, the field with the name userName will have focus
    • <html:form action=“/logon.do&quot; focus=&quot;userName&quot;>
  • 118. Submit Buttons
    • <html:submit value=“Submit”/>
    • Must be in between html:form tags
    • May have multiple submits.
      • There are several ways to deal with multiple submits
        • Checking different values in an action
        • Javascript magic
        • Using the DispatchAction with the property attribute of the submit button
      • We’ll address some of these in the advance forms handling section.
  • 119. Text Fields
    • <html:text property=“userName” />
    • This tag performs the following:
      • On JSP forward
        • Gets the value of the form beans getUserName() method
        • Creates an html input tag
        • Defaults the value of the input to the value retrieved.
      • On Submit
        • Gets the value of the input tag
        • Sets the value of the like named property in the form bean
  • 120. Combo Boxes
    • <html:select property=“employee”>
    • Used to create an html select in order to create a combo box
  • 121. Combo Box
    • This tag performs the following:
      • On JSP forward
        • Gets the value of the form beans getEmployee() method
        • Creates an html select tag
        • Defaults the value of the select tag to the value retrieved.
        • If there isn’t an option that matches the select choice then it’s up to the browser to decide
      • On Submit
        • Gets the option selected
        • Sets the value of the like named property in the form bean
  • 122. HTML Selects
    • Observations for the example below
      • The name of the select is employees
      • The default value is Ken, Ken will be displayed in the drop down
      • The list will have Ken, Tammy and Amanda
      • The value of Tammy is 102
      • The value of Amanda is Amanda
    • <select name=&quot;employees&quot;>
    • <option value=&quot;101&quot; selected=&quot;selected&quot;>Ken</option>
    • <option value=“102”>Tammy</option>
    • <option >Amanda</option>
    • </select>
  • 123. Options for the Drop Down
    • Hard-Coded String
      • Struts
      • Html
    • Array of Strings
    • Collections
    • You can hard code the value of the dropdown as well. For example:
    • <html:select property=“employee” value=“Ken”>
    • In this case the value of employee is ignored.
  • 124. Hard-Coded Options
    • In this example the options of the select are hard coded in the JSP
      • The value and name are the same
      • Produces: <option value=“Ken”>Ken</option>
    • <html:select property=“employee”>
    • <html:options value=“Ken” />
    • <html:options value=“Amanda” />
    • <html:options value=“Amelia” />
    • </html:select>
  • 125. String Array Options
    • In this example, there is an employeeList property in the form bean which returns a String array.
    • Each elements of the array will be a name and value of an option.
    • <html:select property=“employee”>
    • <html:options name=“employeeList” />
    • </html:select>
  • 126. Collections Options
    • When working with a collection of Java objects which are not Strings
    • Collection: Identifies the collection property name of the form bean
    • Property: is a property on the object in the collection
      • Used for the value of the option.
      • In this case the objects in the collection have a property getEmployeeID()
    • labelProperty: is a property on the object in the collection
      • Used for the label of the option
      • In this case the object is getName()
  • 127. Collections Options
    • Example:
    • <html:select property=“employee”>
    • <html:options collection=“employeeList” property=“employeeID” labelProperty=“name” />
    • </html:select>
  • 128. Employee Class
    • public class Employee {
    • private String name;
    • private String employeeID;
    • public String getName() {
    • return name;
    • }
    • public void setName(String name) {
    • this.name = name;
    • }
    • public String getEmployeeID() {
    • return employeeID;
    • }
    • public void setEmployeeID(String employeeID) {
    • this.employeeID = employeeID; } }
  • 129. Collections Output
    • <html:select property=“employee”>
    • <html:options collection=“employeeList” property=“employeeID” labelProperty=“name” />
    • </html:select>
    • Results in:
    • <select name=&quot;employee&quot;>
    • <option value=&quot;101&quot; >Ken</option>
    • <option value=“102”>Tammy</option>
    • <option value=“102”>Amanda</option>
    • </select>
    Where employeeID for the Ken object is 101 and Ken is the name
  • 130. Radio Button
    • <html:radio property=“status” value=“Full Time” />
    • <html:radio property=“status” value=“Part Time” />
    • Used to create an html set of input type radio buttons
    • This tag performs the following:
      • On JSP forward
        • Gets the value of the form beans getStatus() method
        • Creates an html input tag of type radio
        • Defaults the value to the radio of the same value
      • On Submit
        • Gets the value of the radio
        • Sets the value of the like named property in the form bean
    <input type=“radio” name=“status” value=“Full Time” >Full Time</input> <input type=“radio” name=“status” value=“Part Time” > Part Time</input>
  • 131. Check Box
    • <html:checkbox property=“isUSCitizen” value=“wasUSCitizen” />
    • Used to create an html input check boxes
    • Properties must be of type booleans
  • 132. Check Box
    • This tag performs the following:
      • On JSP forward
        • Gets the value of the form beans wasUSCitizen() method
        • Creates an html input tag of type checkbox, named isUSCitizen
        • Defaults the value to the checkbox to the value of wasUSCitizen()
      • On Submit
        • Gets the value of the checkbox
        • Sets the value of the isUSCitizen property in the form bean
    • If you don’t need a default value you don’t need to use a value attribute.
  • 133. Multibox
    • Use almost every time you have a SET of checkboxes
    • This provides an easy solution for working with multiple selections.
    • Works with String Arrays NOT booleans.
    • Typically used in an iterator.
      • Use the multibox tag with the same property name for all checkboxes which are apart of the multibox.
    • Reference: http://husted.com/struts/tips/007.html
  • 134. Multibox Tag
    • <html:multibox property=&quot;benefits&quot;>401K</html:multibox>401K
    • <html:multibox property=&quot;benefits&quot;>Health</html:multibox>Health
    • <html:multibox property=&quot;benefits&quot;>Dental</html:multibox>Dental
    • The property benefits is a String array
    • It will have a String element for each property checked.
    • It can also be used to default the values on form display
    <input type=&quot;checkbox&quot; name=&quot; benefits&quot; value=&quot;401K&quot;>401K <input type=&quot;checkbox&quot; name=&quot; benefits&quot; value=“Health&quot;>Health <input type=&quot;checkbox&quot; name=&quot; benefits&quot; value=“Dental&quot;>Dental
  • 135. Multi-Box Example
    • <logic:iterate id=“employee&quot; property=“employees&quot;>
    • <html:multibox property=“selectedEmployees&quot;>
    • <bean:write name=“employee“ property=“employeeID”/>
    • </html:multibox>
    • <bean:write name=“employee“ property=“name”/>
    • </logic:iterate>
  • 136. Multi-Box Example
    • Using the Employee Object previously discussed
    • The iterate tag will go through all Elements of the collection provided by getEmployees()
    • Each element will be referenced by the name “employee”
    • There will be a checkbox created for each element
      • Value = employeeID
      • Text = name
  • 137. Working with Tables
    • This is more about working with rows of data.
    • Displaying our employee information in a table.
    • <table>
    • <tr><th>Employee ID</th><th>Employee Name</th></tr>
    • <logic:iterate id=“employee&quot; property=“employees&quot;>
    • <tr>
    • <td><bean:write name=“employee“ property=“employeeID”/></td>
    • <td><bean:write name=“employee“ property=“name”/> </td>
    • </tr>
    • </logic:iterate>
    • </table>
  • 138. Tables With Nested Tags
    • <table>
    • <tr><th>Employee ID</th><th>Employee Name</th></tr>
    • <nested:iterate property=“employees&quot;>
    • <tr>
    • <td><nested:write property=“employeeID”/></td>
    • <td><nested:write property=“name”/> </td>
    • </tr>
    • </nested:iterate>
    • </table>
    Produces the same results Nested Iterate tag, creates a temporary ID for us. The nested writes, use the temporary ID.
  • 139. Advanced Forms
  • 140. DispatchActions
    • Using the submit buttons to select which dispatch action to use:
    • Assume:
      • Struts-Config.xml
      • <action name=“Employee&quot; type=&quot;com.codementor.EmployeeAction&quot; parameter=&quot;action&quot; scope=&quot;request&quot; path=&quot;/employee&quot;>
      • Action Class has the following methods:
        • add()
        • save()
  • 141. Dispatch JSP
    • <html:form action=&quot;/employee.do&quot;>
    • <html:submit value=&quot;add&quot; property=&quot;action&quot;/>
    • <html:submit value=&quot;save&quot; property=&quot;action&quot;/>
    • </html:form>
    Produces a /employee.do?action=add For the add submit button
  • 142. JavaScript Action Switch
    • Example:
      • <html:image src=“images/emp_button_run_model.gif” onclick=“document.forms[0].action=‘runModel.do” border=“0” />
  • 143. Struts Classes
  • 144. Struts Classes
    • ImageButtonBean
    • LabelValueBean
    • RequestUtil
    • Jakarta Commons
      • BeanUtil
  • 145. ImageButtonBean
    • Provides the X and Y coordinates of where on an image the mouse was clicked.
    • Properties:
      • X
      • Y
      • isSelected
    • A Property of this type in the form bean can provide this information
  • 146. LabelValueBean
    • Utility Class to provide a different display name from the selection name.
    • How do we produce the following html:
    • <select name=“listType”>
    • <option value=“ST”>Standard
    • <option value=“SL”>Select
    • </select>
  • 147. LabelValueBean Ex
    • JSP Code
    • <html:select property=“type”>
    • <html:options collection=“listTypes” property=“value” labelProperty=“label” />
    • </html:select>
    • Java Code
    • Form.addListTypes(new LabelValueBean(“Standard”,”ST”));
    • Form.addListTypes(new LabelValueBean(“Select”,”SL”));
  • 148. RequestUtil
    • Utility for working with the request object.
    • Provides:
      • actionURL
      • absoluteURL
      • createActionForm
      • URL encoding
      • Access to ActionErrors
      • Access to Action Mappings
      • Printable URL
  • 149. BeanUtil
    • Was part of Struts 1.0
    • Now part of Jakarta Commons
      • Which is included with Struts 1.1
    • Great Utility to copy values of the properties of one bean to the values of the properties of the same name of another bean.
  • 150. Summary
    • Common Tags
    • Working with Forms
      • Most data input tags were discussed.
    • Useful Struts Java Classes
  • 151. Questions?
  • 152. Struts Validation
  • 153. Section Agenda
    • Simple Bean Validation
    • Understanding Validation Framework
    • Business Level Validation
  • 154. Validation Opportunities
    • Client-Side
      • javascript
    • Server-Side
      • Form Bean
      • Action Class
      • Validator Framework
  • 155. Client Side Validation
    • In addition to your own javascript, Struts provides the ability to generate javascript based on configuration.
      • Discussed further in validator framework
    • Javascripts Pros:
      • Convenience to the client
      • Provides a network throttle
    • Javascript cons:
      • Multi-Browser support
  • 156. Server-Side Validation
  • 157. Server-Side Validation
    • Common Validation Classes and Configuration
    • Form Bean Validation
    • Action Bean Validation
  • 158. Validation Framework Classes
    • ActionErrors
      • Used in struts to contain all the errors from a validation point
    • ActionError
      • A specific validation error, which will be put in the ActionErrors
      • Contains an error key (which may be used with the resourse bundle)
  • 159. Resource Messages
    • Application.properties file configured with the message-resources tag in the struts-config.xml
    ApplicationResources.properties file: error.username.required=Username is required error.password.required=Password is required Struts-config.xml file snip: <message-resources parameter=&quot;com.codementor.ApplicationResources&quot; />
  • 160. A Look at MessageFormat
    • It’s required for the validation framework to under the java.text.MessageFormat class.
    • Provides a way to have parameterized message
      • Single digit values from 0-9 are used as place holders in a String text.
        • {0},{1},{2},…
      • These provides the ability to have a generic message where specifics can be inserted in the message at a latter time.
  • 161. Message Format Ex.
    • Example Message:
    • String message = &quot;The disk named {0} contains {1} files.&quot;;
    • String[] args = {&quot;Foo&quot;,&quot;300&quot;};
    • System.out.println(MessageFormat.format(message,args));
    • Output:
    • The disk named Foo contains 300 files.
  • 162. Server-Side Validation
    • Common Validation Classes and Configuration
    • Form Bean Validation
    • Action Bean Validation
  • 163. Form Bean Validation
    • In order to validate a form bean the following conditions must exist:
      • The validate method of the form bean must be implemented.
      • The form bean must be configured in the configuration file to use validation
        • This is configured by action class.
    • The validation occurs prior to the action class being invoked.
      • If there is an error the client is redirected to the configured input page.
  • 164. Validate() Method
    • public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
    • ActionErrors errors = new ActionErrors();
    • if ( (userName == null) || (userName.length() < 1)) {
    • errors.add(&quot;userName&quot;, new ActionError(&quot;error.username.required&quot;));
    • }
    • return errors;
    • }
    ApplicationResources.properties file: error.username.required=Username is required error.password.required=Password is required
  • 165. Validate Method
    • Return ActionErrors.size() == 0 or return null if there are no errors
    • Add Errors to the ActionErrors for each error
    • The keys map to the properties in the configured property file.
  • 166. Bean Validation Config
    • <action input=&quot;/Login.jsp&quot; name=&quot;logonForm&quot; path=&quot;/logon&quot; scope=&quot;request&quot; type=&quot;com.codementor.LogonAction&quot; validate=&quot;true“ >
    • <forward name=&quot;success&quot; path=&quot;/Success.jsp&quot; redirect=&quot;true&quot; />
    • <forward name=&quot;failure&quot; path=&quot;/Failure.jsp&quot; />
    • </action>
    • The validate = true will cause the validate() method to be invoked on the form bean that is configured for this action.
    • This occurs when this action is invoked from the client side, but just prior to the actual execution of the action class.
  • 167. Server-Side Validation
    • Common Validation Classes and Configuration
    • Form Bean Validation
    • Action Bean Validation
  • 168. Action Bean Validation
    • Validation in the Action class
    • Requires a little more handling on the developers part
    • Typical Reasons:
      • Business logic validation
      • Navigation dependencies
        • Forwards needs to go somewhere other than the input.
  • 169. Example Action Validation
    • public ActionForward execute( …) {
    • LogonForm form = (LogonForm) actionForm;
    • ActionErrors errors = new ActionErrors();
    • if ( form.getUserName().length() < 1)
    • errors.add(&quot;userName&quot;, new ActionError(&quot;error.username.required&quot;));
    • if ( form.getPassword().length() < 1)
    • errors.add(&quot;password&quot;, new ActionError(&quot;error.password.required&quot;));
    • saveErrors(request,errors);
    • return mapping.findForward(forward);
    • // the forward would need to be set
    • }
  • 170. Validation Framework
  • 171. Validation Framework
    • Configured in XML
    • Rules defined in XML
    • Pre-defined validators
    • User-defined validators
    • Can be configured to provide javascript to the client
    • Must use the ValidatorForm
    • Works with Resource Bundle
  • 172. XML Configuration
    • Although there can be any number of files used for validation configuration, there are typically 2:
      • Validation-rules.xml
        • Contains the xml defined rules
        • Typically generic / Non application specific
        • Provided with the struts download
      • Validation.xml
        • Configuration of the rules from the first xml file, to the forms and fields defined in the struts-config file.
        • Typically application specific.
  • 173. Validation-rules.xml
    • <validator name= &quot;required&quot;
    • classname=&quot;org.apache.struts.validator.FieldChecks&quot;
    • method=&quot;validateRequired&quot;
    • methodParams=&quot;java.lang.Object,
    • org.apache.commons.validator.ValidatorAction,
    • org.apache.commons.validator.Field,
    • org.apache.struts.action.ActionErrors,
    • javax.servlet.http.HttpServletRequest&quot;
    • msg=&quot;errors.required&quot;>
    • <javascript><![CDATA[ …
  • 174. Configure Validation Example
    • Create the Validation.xml
    • Configure the struts application to use the validation framework
    • Create or Copy the applications.properties file
    • Configure the application.properties file in the struts configuration file
    • Configure the output location to show the error
  • 175. Validation.xml Username Ex
    • <form-validation >
    • <formset>
    • <form name=&quot;logonForm&quot; >
    • <field
    • property=&quot;userName&quot;
    • depends=&quot;required&quot; />
    • </form>
    • </formset>
    • </form-validation >
    ApplicationResources.properties file: errors.required={0} is required
  • 176. Validation Config
    • Entry in the struts-config.xml file.
    • Configured with the ValidatorPlugin.
    • The pathnames properties is just a comma separated list of all the xml files that are needed for this applications validation purposes.
    • <plug-in className=&quot;org.apache.struts.validator.ValidatorPlugIn&quot;>
    • <set-property property=&quot;pathnames&quot;
    • value=&quot;/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml&quot; />
    • </plug-in>
  • 177. Application.properties File
    • #Struts Validator Basic Error Message
    • errors.required={0} is required.
    • errors.minlength={0} can not be less than {1} characters.
    • errors.maxlength={0} can not be greater than {1} characters.
    • errors.invalid={0} is invalid.
    • errors.byte={0} must be an byte.
    • errors.short={0} must be an short.
    • errors.integer={0} must be an integer.
    • errors.long={0} must be an long.
    • errors.float={0} must be an float.
  • 178. Property File Configuration
    • Configure the property file in the struts-config.xml file
    • This example assumes that it is the WEB-INF/classes/com/codementor directory of the web application.
    • <message-resources parameter=&quot;com.codementor.Application&quot; />
  • 179. Displaying Strut Errors
    • <html:errors/>
      • Errors are displayed where this tag is placed in the JSP file.
    • <html:errors property=“userName”/>
      • Placing errors close to the property of choice
      • Displays only the errors for this property
  • 180. Pre-Defined Validators
  • 181. Pre-Defined Validators
    • Required
    • minLength
    • maxLength
    • Range
    • Date
    • Basic types (integer, long, double, float )
    • Email
      • Validates that the email could be valid
    • creditCard
      • Validates that the number could be valid
    • Mask
      • Used to check regular expression
  • 182. Default Property Keys
    • #Struts Validator Basic Error Message
    • errors.required={0} is required.
    • errors.minlength={0} can not be less than {1} characters.
    • errors.maxlength={0} can not be greater than {1} characters.
    • errors.invalid={0} is invalid.
    • errors.byte={0} must be an byte.
    • errors.short={0} must be an short.
    • errors.integer={0} must be an integer.
    • errors.long={0} must be an long.
    • errors.float={0} must be an float.
    • errors.double={0} must be an double.
  • 183. Default Property Keys
    • errors.date={0} is not a date.
    • errors.range={0} is not in the range {1} through {2}.
    • errors.creditcard={0} is not a valid credit card number.
    • errors.email={0} is an invalid e-mail address.
  • 184. MinLength Configuration
    • <field property=“userName“ depends=&quot;minlength&quot;>
    • <arg0 key=“userName“ resource=“false”/>
    • <arg1 name=&quot;minlength&quot;
    • key=&quot;${var:minlength}&quot; resource=&quot;false&quot;/>
    • <var>
    • <var-name>minlength</var-name>
    • <var-value>5</var-value>
    • </var>
    • </field>
    ApplicationResources.properties file: errors.minlength={0} can not be less than {1} characters.
  • 185. MaxLength Configuration
    • <field property=“userName“ depends=&quot;maxlength&quot;>
    • <arg0 key=“userName“ resource=“false”/>
    • <arg1 name=&quot;maxlength&quot;
    • key=&quot;${var:maxlength}&quot; resource=&quot;false&quot;/>
    • <var>
    • <var-name>maxlength</var-name>
    • <var-value>5</var-value>
    • </var>
    • </field>
    ApplicationResources.properties file: errors.maxlength={0} can not be greater than {1} characters.
  • 186. Range Configuration
    • <field property=“priorty“ depends=“range&quot;>
    • <arg0 key=“responseForm.priority.displayname“ />
    • <arg1 name=“range&quot; key=“${var:min}” resource=&quot;false&quot;/>
    • <arg2 name=“range&quot; key=“${var:max}” resource=&quot;false&quot;/>
    • <var>
    • <var-name>min</var-name>
    • <var-value>1</var-value>
    • </var>
    • <var>
    • <var-name>max</var-name>
    • <var-value>4</var-value>
    • </var>
    • </field>
    ApplicationResources.properties file: errors.range={0} is not in the range {1} through {2}.
  • 187. Date Configuration
    • <field property=“date“ depends=“date&quot;>
    • <arg0 key=“responseForm.date.displayname“ />
    • <var>
    • <var-name> datePattern </var-name>
    • <var-value>MM/dd/yyyy</var-value>
    • </var>
    • </field>
    ApplicationResources.properties file: errors.date={0} is not a date.
  • 188. Double Configuration
    • <field property=“amount“ depends=“double&quot;>
    • <arg0 key=“responseForm.amount.displayname“ />
    • </field>
    ApplicationResources.properties file: errors.double={0} must be an double.
  • 189. CreditCard Configuration
    • <field property=“creditCard“ depends=“creditCard&quot;>
    • <arg0 key=“responseForm.creditCard.displayname“ />
    • </field>
    ApplicationResources.properties file: errors.creditcard={0} is not a valid credit card number.
  • 190. Mask Configuration
    • <field property=“postalCode“ depends=“mask&quot;>
    • <arg0 key=“responseForm.postal.displayname“ />
    • <var>
    • <var-name>mask</var-name>
    • <var-value>^d{5}*$</var-value>
    • </var>
    • </field>
    ApplicationResources.properties file: errors.invalid={0} is invalid.
  • 191. Common Masks
    • Phone
      • ^(?(d{3}))?[-| ]?(d{3})[-| ]?(d{4})$
    • Zip
      • ^d{5}d*$
      • ^d{5}(-d{4})?$
  • 192. Additional Validation Configuration Options
  • 193. Using Global Constants
    • It is possible to define global constants in the validation configuration file.
    • <form-validation>
    • <global>
    • <constant>
    • <constant-name>zip</constant-name>
    • <constant-value>^d{5}d*$</constant-value>
    • </constant>
    • </global>
    <var> <var-name>mask</var-name> <var-value>${zip}</var-value> </var>
  • 194. Configure Multiple Rules
    • <form-validation >
    • <formset>
    • <form name=&quot;logonForm&quot; >
    • <field property=&quot;userName“ depends=&quot;required,mask&quot; >
    • <arg0 key=“logon.username.displayname” />
    • <var>
    • <var-name>mask</var-name>
    • <var-value> ^[a-zA-Z0-9]*$</var-value>
    • </var>
  • 195. Configure a Message
    • <form-validation >
    • <formset>
    • <form name=&quot;logonForm&quot; >
    • <field property=&quot;userName“ depends=&quot;required,mask&quot; >
    • <msg name=“mask” key=“logon.username.maskmsg”/>
    • <arg0 key=“logon.username.displayname” />
    • <var>
    • <var-name>mask</var-name>
    • <var-value> ^[a-zA-Z0-9]*$</var-value>
    • </var>
  • 196. Summary
    • Different levels of validation
    • Leveraging the validation framework
    • Pre-Defined Validators
  • 197. Questions?
  • 198. Struts Tiles
  • 199. Presentation Agenda
    • Tiles Configuration
    • Tile Definitions and Extensions
  • 200. Why Tiles
    • Frame look without frames
    • Consistent look across application
    • Reduce maintainance
    • A better way to “include” a JSP file
  • 201. What is a Tile?
    • An area or region with in a web page.
    Header Footer Left Nav Body
  • 202. Configuration Requirements
    • Struts Configuration
      • TilesRequestProcessor
      • TilesPlugin
    • Tiles Definition XML File
    • Required Jars
      • tiles.jar
      • commons-digester.jar
      • commons-beanutils.jar
      • commons-collections.jar
      • commons-logging.jar
  • 203. TilesRequestProcessor
    • Extends the RequestProcessor to provide per request processing of the forwards.
      • Evaluates the forward to see if it is a tile forward.
    • Required for Tiles to work
    • Struts-config.xml
    • <struts-config>
    • <controller processorClass=&quot;org.apache.struts.tiles.TilesRequestProcessor&quot; />
    • </struts-config>
  • 204. TilesPlugin
    • Checks to see that the configured controller is an instance of the TilesRequestProcessor. If it is not it will remove the request processor and replace it with the TilesRequestProcessor.
    • Struts-Config.xml File
    • <plug-in className=&quot;org.apache.struts.tiles.TilesPlugin&quot;>
    • <set-property property=&quot;definitions-config&quot; value=&quot;/WEB-INF/tiles-defs.xml&quot; />
    • </plug-in>
    • Definitions-config is a required property for the TilesPlugin
  • 205. TilesPlugin Parameters
    • definitions-config
      • Used to configure the tiles xml files.
      • Example: “/WEB-INF/tiles-defs.xml“
    • definitions-debug
      • Sets logging level for debug informion
        • 0 = No Debug (default)
        • 1 = Partial Debug
        • 2 = Full Debug
  • 206. TilesPlugin Parameters
    • definitions-parser-details
      • Logging levels for the commons digestor
    • definitions-parser-validate
      • Validates the configured Tiles XML file with the DTD if set to “true”
    • definitions-factory-class&quot; value=&quot;com.codementor.TilesFactory“
      • Allows you to specify a custom factory
      • It must implement the ComponetDefinitionsFactory Interface.
  • 207. Creating A Tiles Definition File
  • 208. Tiles Definition File
    • Typical naming convention: tiles-def.xml
    • Template:
    • <?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?>
    • <!DOCTYPE tiles-definitions PUBLIC &quot;-//Apache Software Foundation//DTD Tiles Configuration 1.1//EN&quot; &quot;http://jakarta.apache.org/struts/dtds/tiles-config_1_1.dtd&quot;>
    • <tiles-definitions>
    • </tiles-definitions>
  • 209. Tile Definition Tag Details
    • There is only one tag used under the tiles-definition node.
    • <definition name=“” … />
    • Attributes of the definition tag
      • Name – defines the name of the tile
      • Path – defines the layout to be used for this tile
      • Extends – defines a tile to “inherit” properties
      • controllerClass – class name of a TilesAction, called prior to the page include.
      • controllerUrl – url of a controller
      • Roles – if the user is in the specific role it is included, otherwise it is ignored
  • 210. Definition Tag – Sub Tags
    • description
    • display-name
    • Icon
    • put
      • Used to assign a value to defined attribute in the Tile.
    • putList
      • Used to create a list of assignments for a Tile.
  • 211. Put Tag
    • The put tag has no children tags
    • Attributes
      • name – name of the attribute to provide a value for.
      • Direct – determines how content is handled, true means content is printed directly
        • Another way of specifying the content type
      • Type – specify the content type
        • String: content is printed directly
        • Page: content is included from specified URL. Name is URL
        • Definition: value is the name of a tile definition
      • value – value to assign to the attribute
  • 212. Layouts
  • 213. Tile Layouts
    • A JSP file created to represent the layout of the pages
      • Usually without content
    Header Footer Left Nav Body Layout.jsp defines Header Footer Left Nav Body Definition in the Tile has a JSP page included for it at run time.
  • 214. Define A Simple Layout
    • <html:html>
    • <head></head>
    • <body bgcolor=&quot;#ffffff&quot;>
    • <!--Header page information -->
    • <tiles:insert attribute=&quot;header&quot;/>
    • <br />
    • <!--Main body page information -->
    • <tiles:insert attribute=&quot;body&quot;/>
    • <br />
    • <!--Footer page information -->
    • <tiles:insert attribute=&quot;footer&quot;/>
    • <br />
    • </body>
    • </html:html>
    header footer body Layout Design
  • 215. Understanding the Value of Extends
  • 216. Closer Look at the Tiles Definition Extensions
    • The next set of slides demonstration an evolution of thought.
    • The conclusion of which will be a model of how to configure the tile-def.xml file.
    • Steps:
      • Configuration of a definition
      • Configuration of a 2 nd definition
      • 1 st Example using extends
      • The creation of an abstract definition
      • Examples 1 and 2 refactored
  • 217. Starting Definitions
    • Example1 Definition
    • <definition name=&quot;example1“ path=&quot;/Layout.jsp&quot;>
    • <put name=&quot;header&quot; value=&quot;/header.jsp&quot;/>
    • <put name=&quot;footer&quot;
    • value=&quot;/footer.jsp&quot; />
    • <put name=&quot;body&quot; value=&quot;/example1.jsp&quot; />
    • </definition>
    • Example1 Definition
    • <definition name=&quot;example2“ path=&quot;/Layout.jsp&quot;>
    • <put name=&quot;header&quot; value=&quot;/header.jsp&quot;/>
    • <put name=&quot;footer&quot;
    • value=&quot;/footer.jsp&quot; />
    • <put name=&quot;body&quot; value=&quot;/example2.jsp&quot; />
    • </definition>
  • 218. Tiles Definition Extension
    • By using the Extends attribute, a definition can “inherit” all the “puts” of the inherited definition.
    • <tiles-definitions>
    • <definition name=&quot;example1&quot; path=&quot;/Layout.jsp&quot;>
    • <put name=&quot;header&quot; value=&quot;/header.jsp&quot; />
    • <put name=&quot;footer&quot; value=&quot;/footer.jsp&quot; />
    • <put name=&quot;body&quot; value=&quot;/example1.jsp&quot; />
    • </definition>
    • <definition name=&quot;example2&quot; extends=&quot;example1&quot;>
    • <put name=&quot;body&quot; value=&quot;/example2.jsp&quot; />
    • </definition>
    • </tiles-definitions>
  • 219. Abstract Definitions
    • A definition which by itself is very used. It is not concrete.
      • Meaning it doesn’t define everything necessary to display a page.
    • Useful to refer to as one of the layout of the site
    • <tiles-definitions>
    • <definition name=&quot;main&quot; path=&quot;/Layout.jsp&quot;>
    • <put name=&quot;header&quot; value=&quot;/header.jsp&quot; />
    • <put name=&quot;footer&quot; value=&quot;/footer.jsp&quot; />
    • </definition>
    Notice there is no body defined.
  • 220. Abstraction Use
    • <definition name=&quot;example1&quot; extends=&quot;main&quot;>
    • <put name=&quot;body&quot; value=&quot;/example1.jsp&quot; />
    • </definition>
    • <definition name=&quot;example2&quot; extends=&quot;main&quot;>
    • <put name=&quot;body&quot; value=&quot;/example2.jsp&quot; />
    • </definition>
    • </tiles-definitions>
  • 221. Additional Configurations
  • 222. Adding a Title to the Layout
    • <html:html>
    • <head>
    • <title> <tiles:getAsString name=“title”/> </title>
    • </head>
    • <body bgcolor=&quot;#ffffff&quot;>
    • <!--Header page information -->
    • <tiles:insert attribute=&quot;header&quot;/>
    • <br />
    • <!--Main body page information -->
    • <tiles:insert attribute=&quot;body&quot;/>
    • <br />
  • 223. Title Configuration
    • <definition name=&quot;example1&quot; extends=&quot;main&quot;>
    • <put name=“title” value=“Example 1 Page”/>
    • <put name=&quot;body&quot; value=&quot;/example1.jsp&quot; />
    • </definition>
    • <definition name=&quot;example2&quot; extends=&quot;main&quot;>
    • <put name=“title” value=“Example 2 Page”/>
    • <put name=&quot;body&quot; value=&quot;/example2.jsp&quot; />
    • </definition>
  • 224. Action Forward to Tiles
    • Struts-config.xml file
    • <action input=&quot;/Login.jsp&quot; name=&quot;logonForm&quot; path=&quot;/logon&quot; scope=&quot;request“ type=&quot;com.codementor.LogonAction&quot; validate=&quot;true&quot;>
    • <forward name=&quot;success&quot; path=&quot;example1&quot; />
    • <forward name=&quot;failure&quot; path=&quot;example2&quot; />
    • </action>
    • Standard forwards where the path is the name of the tile definition.
    • The TilesRequestProcessor determines on the forward that it is a tile definition.
  • 225. Logon Tiles Example
  • 226. Layout.jsp
    • <html:html>
    • <head><title><tiles:getAsString name=&quot;title&quot;/></title></head>
    • <body bgcolor=&quot;#ffffff&quot;>
    • <!--Header page information -->
    • <tiles:insert attribute=&quot;header&quot;/> <br />
    • <!--Main body page information -->
    • <tiles:insert attribute=&quot;body&quot;/> <br />
    • <!--Footer page information -->
    • <tiles:insert attribute=&quot;footer&quot;/> <br />
    • </body>
    • </html:html>
  • 227. Header / Footer Pages
    • header.jsp
    • Welcome to CodeMentor
    • copyright.jsp
    • copyright (c) 2000-2003 Code Mentor, Inc.
  • 228. Login.jsp
    • <%@ taglib uri=&quot;/WEB-INF/struts-html.tld&quot; prefix=&quot;html&quot; %>
    • <html:form action=&quot;logon.do&quot; focus=&quot;userName&quot;>
    • <br>
    • User Name: <html:text maxlength=&quot;16&quot; property=&quot;userName“ size=&quot;16&quot;/><br />
    • Password: <html:text maxlength=&quot;16&quot; property=&quot;password“ size=&quot;16&quot;/><br />
    • <html:submit value=&quot;Submit&quot; property=&quot;Submit&quot;/>
    • <html:reset value=&quot;Reset&quot;/>
    • </html:form>
  • 229. Success / Failure Pages
    • Success.jsp
    • <h1>
    • Successful Login
    • </h1>
    • Failure.jsp
    • <h1>
    • Failed Login
    • </h1>
  • 230. Tiles Configuration
    • <?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?>
    • <!DOCTYPE tiles-definitions PUBLIC &quot;-//Apache Software Foundation//DTD Tiles Configuration 1.1//EN&quot; &quot;http://jakarta.apache.org/struts/dtds/tiles-config_1_1.dtd&quot;>
    • <tiles-definitions>
    • <definition name=&quot;main&quot; path=&quot;/Layout.jsp&quot;>
    • <put name=&quot;footer&quot; value=&quot;/copyright.jsp&quot; />
    • <put name=&quot;header&quot; value=&quot;/header.jsp&quot; />
    • <put name=&quot;body&quot; />
    • </definition>
  • 231. Tiles Config
    • <definition extends=&quot;main&quot; name=&quot;login.page&quot;>
    • <put name=&quot;body&quot; value=&quot;/Login.jsp&quot; />
    • <put name=&quot;title&quot; value=&quot;Logon Page&quot; />
    • </definition>
    • <definition extends=&quot;main&quot; name=&quot;success.page&quot;>
    • <put name=&quot;body&quot; value=&quot;/Success.jsp&quot; />
    • <put name=&quot;title&quot; value=&quot;Success Page&quot; />
    • </definition>
  • 232. Struts-Config.xml
    • <struts-config>
    • <form-beans>
    • <form-bean name=&quot;formBean&quot; type=&quot;com.codementor.LogonForm&quot; />
    • </form-beans>
    • <action-mappings>
    • <action path=&quot;/loginPage&quot; forward=&quot;login.page&quot; />
    • <action input=&quot;/loginPage.do&quot; name=&quot;formBean&quot; path=&quot;/logon&quot; type=&quot;com.codementor.LogonAction&quot;>
    • <forward name=&quot;success&quot; path= &quot;success.page&quot; />
    • <forward name=&quot;failure&quot; path= &quot;failure.page&quot; />
    • </action>
    • </action-mappings>
  • 233. LogonForm
    • package com.codementor;
    • import org.apache.struts.action.*;
    • public class LogonForm extends ActionForm {
    • private String password;
    • private String userName;
    • public String getPassword() { return password; }
    • public void setPassword(String password) { this.password = password; }
    • public String getUserName() { return userName; }
  • 234. LogonAction
    • package com.codementor;
    • import javax.servlet.http.*;
    • import org.apache.struts.action.*;
    • public class LogonAction extends Action {
    • public ActionForward execute( …) {
    • LogonForm logonForm = (LogonForm) actionForm;
    • String forward = &quot;failure&quot;;
    • if(logonForm.getUserName().equals(&quot;mentor&quot;))
    • { forward = &quot;success&quot;; }
    • return mapping.findForward(forward);
    • }
    • }
  • 235. Demo Results
  • 236. Summary
    • Requirements for Tiles
    • How Tiles Works
    • Tiles Best Practices
    • Full Tiles Example
  • 237. Questions?
  • 238. Thank You
    • 3004
    • Java Web Development with Struts and Tiles
    • Please fill out the speaker evaluation
    • You can contact me further at … [email_address]