Presentation is loading. Please wait.

Presentation is loading. Please wait.

3004 Java Web Development with Struts and Tiles Ken Sipe Chief Instructor / TO Code Mentor.

Similar presentations


Presentation on theme: "3004 Java Web Development with Struts and Tiles Ken Sipe Chief Instructor / TO Code Mentor."— Presentation 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 JSP1JSP3 JSP4 Presentation Present. CtrlPresentation Logic Present. Ctrl 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 JSP2 JSP1JSP3 LogicControl 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.

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 (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 action org.apache.struts.action.ActionServlet debug 2 config /WEB-INF/struts-config.xml … action *.do 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 XML configuration file Allows for: –DataSource definition –Logical name definitions for Forms –View mappings Local Global

20 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” Strut-config.xml { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://images.slideplayer.com/14/4334620/slides/slide_20.jpg", "name": "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.", "description": "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 Strut-config.xml

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="failure"; if(theForm.getUserName().equals("borcon")) { forward="success"; } 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 Logon Form User Name: password: { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://images.slideplayer.com/14/4334620/slides/slide_23.jpg", "name": "Strut Powered JSP Logon Form User Name: password:

24 Creating Your First Struts Application

25 Struts Installation Downlad the zip –http://apache.mirrors.hoobly.com/jakarta/strut s/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 Step 6: Configure web.xml with the ActionServlet

28 JSP Pages Three Pages –Login Page –Success Page –Failure Page

29 Logon Page – HTML Version Login Form User Name: Password:

30 Logon Page – Struts Login Form User Name: Password: Added a cool feature

31 Success and Failure Pages Success.jsp Success Successful Login Failure.jsp Failure Failed Login

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

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 = "failure"; if(logonForm.getUserName().equals("mentor")) { forward = "success"; } return mapping.findForward(forward); }

35 Action Class Config …

36 Map The Forwards …

37 Struts in web.xml action org.apache.struts.action.ActionServlet config /WEB-INF/struts-config.xml debug 2 2 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 action *.do

39 Configure Tags … /WEB-INF/struts-bean.tld /WEB-INF/struts-html.tld

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 validate="true" tUsed to provide validation tOnly called if configured in the struts- config.xml file. tCalled prior to the action class tReturn 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

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("userName");

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

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 (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 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", “login"); map.put(“send.password.button", “sendPassword"); 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?actio n=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 –Short-Hand XML

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 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 tag (discussed later) …

75 Forward to Actions It is common to have a forward go to another action class.

76 Forward Redirects By default forwards are forwards and not redirects. To redirect the client

77 Struts Configuration File

78 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

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.

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.

83 Global Forwards Location of forwards defined to be global. Provides default forward.

84 Action Mappings Action mappings is where the actions are configured. Maps the action to the form bean. Provides local forwards.

85 Controller Configuration of the RequestProcessor for this struts application module. Provides customization to requests. Commonly used for Tiles.

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

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

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 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 Uses the defined global forwards from the struts configuration file. –Page –HREF Required for javascript Back –Action { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://images.slideplayer.com/14/4334620/slides/slide_98.jpg", "name": "Struts Links Preferred order to provide a link in Struts –Forward Uses the defined global forwards from the struts configuration file.", "description": "–Page –HREF Required for javascript Back –Action

99 Links Example Text Link Home Page Image Link

100 Parameterized Links Links which depend on information available through the form bean

101 Parameterized Link Will create a link on the image to: /viewReport.do?model= 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 Or Simply

104

105 Bean:write Used to retrieve a property from: –a form bean –a defined scripted variable (by bean:define)

106 Bean:Write JSP Equivalent: If the named object is an object you do not have to define a property Ex: Ex: 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.

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.

110 Logic:iterate Used to iterate –An array –A Collection All tags between the 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.

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 With nested 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

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 creates a 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

118 Submit Buttons 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 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 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 Ken Tammy Amanda

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:You can hard code the value of the dropdown as well. For example: 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: Ken

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.

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:

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 Results in: Ken Tammy Amanda Where employeeID for the Ken object is 101 and Ken is the name

130 Radio Button 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 Full Time Part Time

131 Check Box 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 401K 401K Health Health Dental 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 401K Health Dental

135 Multi-Box Example

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. Employee ID Employee Name

138 Tables With Nested Tags Employee ID Employee Name 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 Class has the following methods: add() save()

141 Dispatch JSP Produces a /employee.do?action=add For the add submit button

142 JavaScript Action Switch Example:

143 Struts Classes

144 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: Standard Select

147 LabelValueBean Ex JSP Code 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 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:

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 = "The disk named {0} contains {1} files."; String[] args = {"Foo","300"}; System.out.println(MessageFormat.forma t(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("userName", new ActionError("error.username.required")); } 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 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 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("userName", new ActionError("error.username.required")); if ( form.getPassword().length() < 1) errors.add("password", new ActionError("error.password.required")); saveErrors(request,errors); return mapping.findForward(forward); // the forward would need to be set }

170 Validation Framework

171 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 { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://images.slideplayer.com/14/4334620/slides/slide_173.jpg", "name": "Validation-rules.xml

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 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.

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.

179 Displaying Strut Errors –Errors are displayed where this tag is placed in the JSP file. –Placing errors close to the property of choice –Displays only the errors for this property

180 Pre-Defined Validators

181 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 minlength 5 ApplicationResources.properties file: errors.minlength={0} can not be less than {1} characters.

185 MaxLength Configuration maxlength 5 ApplicationResources.properties file: errors.maxlength={0} can not be greater than {1} characters.

186 Range Configuration min 1 max 4 ApplicationResources.properties file: errors.range={0} is not in the range {1} through {2}.

187 Date Configuration datePattern MM/dd/yyyy ApplicationResources.properties file: errors.date={0} is not a date.

188 Double Configuration ApplicationResources.properties file: errors.double={0} must be an double.

189 CreditCard Configuration ApplicationResources.properties file: errors.creditcard={0} is not a valid credit card number.

190 Mask Configuration mask ^\d{5}\*$ 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. zip ^\d{5}\d*$ mask ${zip}

194 Configure Multiple Rules mask ^[a-zA-Z0-9]*$ …

195 Configure a Message mask ^[a-zA-Z0-9]*$ …

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 LeftNavBody

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

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 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" value="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: …

209 Tile Definition Tag Details There is only one tag used under the tiles- definition node. 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 LeftNavBody 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 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 Example1 Definition

218 Tiles Definition Extension By using the Extends attribute, a definition can “inherit” all the “puts” of the inherited definition.

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 Notice there is no body defined.

220 Abstraction Use

221 Additional Configurations

222 Adding a Title to the Layout …

223 Title Configuration

224 Action Forward to Tiles Struts-config.xml file 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

227 Header / Footer Pages header.jsp Welcome to CodeMentor copyright.jsp copyright (c) 2000-2003 Code Mentor, Inc.

228 Login.jsp User Name: Password:

229 Success / Failure Pages Success.jsp Successful Login Failure.jsp Failed Login

230 Tiles Configuration

231 Tiles Config

232 Struts-Config.xml

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 = "failure"; if(logonForm.getUserName().equals("mentor")) { forward = "success"; } 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 … kensipe@codementor.net


Download ppt "3004 Java Web Development with Struts and Tiles Ken Sipe Chief Instructor / TO Code Mentor."

Similar presentations


Ads by Google