Presentation is loading. Please wait.

Presentation is loading. Please wait.

Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Similar presentations


Presentation on theme: "Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla."— Presentation transcript:

1 Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla

2 Agenda Why should you use Struts Installing Struts Struts Concepts What is MVC Configuring Struts Tag libraries Build a practical example What do you do when things go wrong? Advanced Topics

3 Struts Overview

4 Frameworks in general Provide a reusable structure: may serve as a foundation for new products re-usable semi-complete application specialize to produce custom application

5 Model 1 Framework JSP combines the roles of the view and controller components JSP page alone is responsible for processing the incoming request and replying back to the client There is still separation of presentation from content, because all data access is performed using beans Model 1 architecture is perfectly suitable for simple applications but it may not be desirable for complex implementations Indiscriminate usage of this architecture usually leads to a significant amount of scriptlets or Java code embedded within the JSP page

6 Drawbacks of JSP

7 Interweaving scriptlets and HTML results in hard to read and hard to maintain applications. Writing code in JSPs diminishes the opportunity to reuse the code. Of course, you can put all Java methods in a JSP and include this page from other JSPs that need to use the methods. However, by doing so you're moving away from the object-oriented paradigm. For one thing, you will lose the power of inheritance. It is harder to write Java code in a JSP than to do it in a Java class. Let's face it, your IDE is designed to analyze Java code in Java classes, not in JSPs. It is easier to debug code if it is in a Java class. It is easier to test business logic that is encapsulated in a Java class. Java code in Java classes is easier to refactor.

8 Model 2 Framework JSP & Servlets work together in web applications Servlets handle data access & control flow JSP focus on tasks of writing HTML Model contains the core of the application's functionality i.e. business domain encapsulates the state of the application

9 Model 2 Framework View handles the presentation of the business domain can access the model getters, but it has no knowledge of the setters knows nothing about the controller Controller processes the user input to direct the flow and manage user state reacts to the user input creates and sets the model.

10 Classic MVC Pattern 1.Controller mediates application flow 2.Model encapsulates business logic & data 3.View contains presentation logic

11 Struts Framework Characteristics Open source hosted by Apache Based on standard Java/J2EE technologies. Core of struts is flexible controller layer Struts encourages Model 2 application architecture Model View Controller separates responsibilities Struts is a Servlet that supports your applications JSP Pages are also Servlets Struts provides a pluggable framework Tools exist to simplify Struts development

12 Struts – on Model 2, MVC Struts framework based on Model 2 architecture Controller servlet manages flow between JSP pages Special classes help with data access Substantial tag library for JSP pages makes framework easy to use MVC pattern implementation ActionForwards & ActionMappings keep control flow decisions out of the presentation layer

13 Struts Client browser An HTTP request from the client browser creates an event. The Web container will respond with an HTTP response. Controller The Controller receives the request from the browser, and makes the decision where to send the request. With Struts, the Controller is a command design pattern implemented as a servlet. The struts-config.xml file configures the Controller.

14 Struts Business logic The business logic updates the state of the model and helps control the flow of the application. With Struts this is done with an Action class as a thin wrapper to the actual business logic. Model state The model represents the state of the application. The business objects update the application state. The ActionForm bean represents the Model state at a session or request level, and not at a persistent level. The JSP file reads information from the ActionForm bean using JSP tags.

15 Struts View The view is simply a JSP file. There is no flow logic, no business logic, and no model information -- just tags. Tags are one of the things that make Struts unique compared to other frameworks.

16 Benefits Configuration via XML files Many changes can be made without modifying or recompiling Java code Pages are loosely coupled; URLs not hardcoded Form beans Greatly simplifies processing of request parameters HTML tags Lets you get initial values from Java objects Lets you redisplay forms with previous values intact Form field validation Client-side and server-side

17 Benefits Consistent implementation Encourages consistent use of MVC throughout applications which employ JSP Internationalization and Localization Eg. en-us, en-ca, fr-ca Supported through “resources” Usually just a “properties” file i.e. resources.properties

18 When to use Struts In case of a very simple application, with a handful of pages, then you might consider a "Model 1" solution that uses only server pages. With complicated application, with dozens of pages, that need to be maintained over time, then Struts can help

19 Struts – Schematic Overview

20 RELY-ON SOLUTIONS Core Struts Classes

21 ActionMapping Maps a path attribute to that of an incoming URI ActionForward Encapsulates the destination of where to send control upon completion of the Action The destination is detailed in the configuration file: HTML,JSP, servlets

22 Core Struts Classes ActionForm Hold state and behavior for user input using corresponding fields from the HttpServletRequest No more request.getParameter() calls. For instance,the Struts framework will take fname from request stream and call UserActionForm.setFname() Can be used to validate presentation data Should be used to encapsulate data that is for delivery to the data model

23 Core Struts Classes ActionForm is an abstract class that is sub-classed for each input form model represents a general concept of data that is set or updated by a HTML form. E.g., you may have a UserActionForm that is set by an HTML Form Also conducts form state validation can be maintained at a session level

24 Core Struts Classes ActionServlet responsible for packaging and routing HTTP traffic to the appropriate handler takes on administering the behavior of the “Controller” configured via the deployment descriptor of the web application and is typically is configured in the deployment descriptor to accept a pattern of URLs such as *.do uses a configuration file so values are not hard-coded Java developer does not need to recompile code when making flow changes

25 Core Struts Classes Action Classes The RequestProcessor delegate the work to be done to an Action.Provides loose coupling between the user request and the business RequestProcessor Takes on the behavior of the “Controller” by handling the core processing logic Determine the ActionMapping associated with the request and instantiates the Action Instantiates ActionForm if needed Processes the ActionForward

26 Components

27 Struts Controller Controller responsibilities include receiving input from a client, invoking a business operation, and coordinating the view to return back to the client. Of course, there are many other functions that the controller may perform, but these are a few of the primary ones. JSP Model 2 architecture, on which Struts was fashioned the controller was implemented by a Java Servlet.

28 Struts Controller This servlet becomes the centralized point of control for the web application. The controller servlet maps user actions into business operations and then helps to select the view to return to the client based on the request and other state information.

29 Struts Controller

30 In the Struts framework, the controller responsibilities are implemented by several different components, one of which is an instance of the org.apache.struts.action.ActionServlet

31 Action Servlet The ActionServlet extends the javax.servlet.http.HttpServlet class and is responsible for packaging and routing HTTP traffic to the appropriate handler in the framework. The ActionServlet class is not abstract and therefore can be used as a concrete controller by your applications. Prior to version 1.3 of the Struts framework, the ActionServlet was solely responsible for receiving the request and processing it by calling the appropriate handler.

32 Action Servlet In version 1.3, a new class called org.apache.struts.action.RequestProcessor has been introduced to process the request for the controller. Like any other Java servlet, the Struts ActionServlet must be configured in the deployment descriptor for the web application i.e. web.xml. Once the controller receives a client request, it delegates the handling of the request to a helper class. This helper knows how to execute the business operation that is associated with the requested action.

33 Action Class An org.apache.struts.action.Action class in the Struts framework is an extension of the controller component. The Action class decouples the client request from the business model. This decoupling allows for more than a one-to-one mapping between the user request and an Action class. The Action class can perform other functions, such as authorization, logging, and session validation, before invoking the business operation.

34 Action Class The Struts Action class contains several methods, but the most important is the execute() method. public ActionForward execute ( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws IOException, ServletException;

35 Action Class The execute() method is called on an instance of an Action class by the controller when a request is received from a client. The controller will create an instance of the Action class if one doesn’t already exist. The Struts framework will only create a single instance of each Action class in your application. Since there is only one instance for all users, you must ensure that all of your Action classes operate properly in a multi-threaded environment.

36 Action Class

37 execute Each one of the action classes that we’ll create for the application will extend the Struts Action class and override the execute method to carry out the specific operation. it’s best to create an abstract base Action class for your application that all of your other action classes extend. Always extend org.apache.struts.action.Action Class and implement execute() method.

38 Mapping Action At this point, you might be asking yourself, “How does the controller know which Action instance to invoke when it receives a request?” The answer is by inspecting the request information and utilizing a set of action mappings. Action mappings are part of the Struts configuration information that is configured in a special XML file.

39 Mapping Action This configuration information is loaded into memory at startup and made available to the framework at runtime. Each element is represented in memory by an instance of the org.apache.struts.action.ActionMapping class. The ActionMapping object contains a path attribute that is matched against a portion of the URI of the incoming request.

40 Mapping Action <action path="/login" type="com.test.struts.banking.action.LoginAction" scope="request" name="loginForm" validate="true" input="/login.jsp">

41 Mapping Action The login action mapping shown here maps the path “/login” to the Action class com.test.struts.banking.LoginAction. Whenever the controller receives a request where the path in the URI contains the string “/login”, the execute() method of the LoginAction instance will be invoked. The Struts framework also uses the mappings to identify the resource to forward the user to once the action has completed.

42 Determine Next View How or what determines the view to return back to the client ? If you looked closely at the execute() method signature in the Action class from the previous section, you might have noticed that the return type for the method is an org.apache.struts.action.ActionForward class.

43 Determine Next View The ActionForward class represents a destination to which the controller may send control once an Action has completed. Instead of specifying an actual JSP page in the code, you can declaratively associate an action forward mapping with the JSP and then use that ActionForward throughout your application.

44 forward The action forwards are specified in the configuration file, similar to action mappings. They can be defined for a specific action as this forward is for the logout action mapping. <action path="/logout" type="com.test.struts.banking.action.LogoutAction" scope="request">

45 forward The logout action declares a element that is named “Success”, which forwards to a resource of “/login.jsp”. Notice in this case, a redirect attribute is set to “true”. Instead of performing a forward using a RequestDispatcher, the request that invokes the logout action mapping will be redirected instead. The action forward mappings can also be specified in a global section independent of any specific action mapping.

46 Global-forward The forwards defined in the global section are more general and don’t apply to a specific action. Notice that every forward must have a name and path, but the redirect flag is optional. If you don’t specify a redirect attribute, its default value is false and thus performs a forward.

47 Struts Model Components

48 Model Components Using Model components to hide the implementation details for interacting with remote systems is one of the keys to using Struts effectively ActionForm Beans Represent actions that can change that state Java Bean / EJBs Represent internal state & business logic of the system Relational Database Access Struts can define the datasources for an application from within its standard configuration file

49 ActionForm Beans Create one for each input form in the application Extends ActionForm class May be defined in ActionMapping configuration file Typically only has property getters & setters Define property for each field present in the form With associated getXXX() & setXXX() methods Field name & property name must match Place bean instance on form and use nested property references If there’s a customer bean on the Action Form, then refer to the property “customer.name” in JSP This would correspond to methods customer.getName() & customer.setName(String name) on customer bean

50 ActionForm Beans The struts-config.xml file controls which HTML form request maps to which ActionForm Multiple requests can be mapped to an ActionForm ActionForm can be mapped over multiple pages for things such as wizards

51 Role of ActionForm Controller servlet performs following: Check session for instance of bean of appropriate class If no session bean exists, one is created automatically For every request parameter whose name corresponds to name of a property in the bean, corresponding setter method is called Updated ActionForm bean is passed to the Action class perform(), making these values immediately available

52 JavaBeans of EJBs Functional logic of the application: Represented by a set of business logic beans Might be JavaBeans for small applications that access a database using JDBC calls For larger applications these beans will often be stateless or stateful EJBs

53 Struts View Components

54 JSP or HTML pages Use Struts tag library, JSTL tag library DO NOT HARD CODE labels Utilize ResourceBundle Uses beans stored in request or session or application scope

55 Tag Libraries

56 Struts Tag Libraries taglib directive: Tells JSP compiler, where to find the tag library descriptor for the struts tag library

57 Struts Tag Libraries Tag Library Descriptor Purpose struts-html.tldJSP tag extension for HTML forms struts-bean.tldJSP tag extension for handling JavaBeans struts-logic.tld JSP tag extension for testing the values of properties

58 Overview Number of taglibs included as part of Struts Usage is not required, but helpful Bean tags Tags for accessing Beans and their properties Html tags Form bridge between JSP view and other components Logic tags Provides presentation logic tags that eliminate need for scriptlet Template tags (Tiles in v1.1) Tags to form JSP templates that include parameterized content

59 Overview All tag libs are defined in web.xml using element /WEB-INF/struts -bean.tld /WEB-INF/struts -html.tld

60 Bean Tags Tags for accessing beans and their properties Enhancements to Convenient mechanisms to create new beans based on the value of: Cookies Request Headers Parameters

61 HTML Tags Form bridge between JSP view and other components Input forms are important for gathering data Most of the actions of the HTML taglib involve HTML forms Error messages, hyperlinking, internationalization In ActionForm Class ActionErrors errors = new ActionErrors(); if ((username == null) || (username.length() < 1)) errors.add("username", new ActionError("error.username.required"));

62 HTML Tags In JSP write <html:text property="username" size="16" maxlength="16"/>

63 tag The tag provides convenience and a great deal of flexibility if it makes sense for your application to URL encode request parameters. It also automatically handles URL encoding of Session IDs to ensure that you can maintain session state with users who have cookies turned off in their browser. Go Home The HTML generated is Go Home Create Link by Specifying a Full URL Generate an “href” directly

64 The Basics of Form Processing This section provides information on the following tags: - Render an HTML element - T ext box INPUT element — INPUT type=hidden element

65 — Place a Submit INPUT element — Place a Submit INPUT element which can be used to “cancel” workflow

66 Form tags Generates HTML:

67 Generates:

68 Where address is a form bean property which will be set with a selected value addresses – Collection type property for inputs

69 Logic Tags Provides presentation logic tags that eliminate need for scriptlets Value comparisons Include: = != = Substring matching match, notmatch Presentation logic forward, redirect Collections iterate

70 Template Tags Templates are JSP pages that include parameterized content Useful for creating dynamic JSP templates for pages that share a common format Three template tags work in an interrelated function: Get Insert Put Layout various tiles of a web page Header, Navigation, Body, Footer Specified in tiles-definition.xml Specifies the layout Logical names for various tiles Associate filenames to the tiles

71 Resource Bundles Extends basic approach of java.util.ResourceBundle org.apache.struts.util.MessageResources Allows specification of dynamic locale key on a per user basis Limited to presentation, not input Configure resource bundles in web.xml file Configures message resource bundles All static strings should be specified in myApplication.properties file Format: key=value Name.label=Enter first name

72 Automatic Form Validation Validation with ActionForm Struts automatically validates inputs from the form Override a stub method Provides error messages in the standard application resource To utilize this feature Override the validate() method in ActionForm class

73 Automatic Form Validation public ActionErrors validate(ActionMapping map, HttpServletRequest req) { ActionErrors errors = new ActionErrors(); if (name==null || name.length() < 1) errors.add(“nameMissing”, new ActionError(“msg.key”)); return errors; }

74 Automatic Form Validation validate() is called by controller servlet After bean properties have been populated Before corresponding Action class’s validate() method is invoked Add the following to Input page

75 Validator Package Automatically generate client side JavaScript code Specify WEB-INF/validation.xml Define regular expressions for validating data, phone#, social security#, etc. For each form specify required fields Augment rules in WEB-INF/validator- rules.xml

76 No need to write ActionForm Dynamically generate ActionForm class for your forms Specify form fields in struts-config.xml Basic idea is properties of a bean are a HashMap Again check Jakarta Commons Project

77 Struts Controller Components

78 Controller Components ActionServlet Controller servlet which implements primary function of mapping a request URI to an Action class Action class Extension of the Action class For each logical request that may be received In struts-config.xml Action mapping used to configure the controller servlet In web.xml Include the necessary Struts components

79 Action Class The primary method that must be written in an Action class is the execute() method Defines the execute() method that is overridden The framework calls execute() method after the form bean is populated and validated correctly Goal of an Action class is to: Process this request and then to return an ActionForward object, that identifies the JSP page (if any) to which control should be forwarded to generate corresponding response

80 Typical logic in execute() method If validation has not yet occurred, validate the form bean properties as necessary Update server side objects that will be used to create the next page of the user interface Return an appropriate ActionForward object that identified JSP page to be used to generate this response, based on the newly updated beans

81 Typical logic in execute() method The signature of the execute() method in any Action class: public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {

82 Typical logic in execute() method ActionMapping mapping The ActionMapping provides access to the information stored in the configuration file (struts-config.xml) entry that configures this Action class ActionForm form This is the form bean. By this time, the form bean has been prepopulated and the validate() method has been called and returned with no errors (assuming that validation is turned on). All the data entered by the user is available through the form bean.

83 Typical logic in execute() method HttpServletRequest request This is the standard JSP or Servlet request object. HttpServletResponse response This is the standard JSP or Servlet response object.

84 Design Issues One instance of Action class used for all requests Action class should operate correctly in multi- threaded environment Important principle that aids thread-safe coding Use only local variables, not instance variables

85 Design Issues Model Beans may throw exceptions Trap all such exceptions in the logic of execute() method, and log them to application log file As a general rule Allocating scarce resources and keeping them across requests from same user (in user’s session) can cause scalability problems

86 Struts Configuration

87 ApplicationResources.properties Stores localized messages & labels struts-config.xml Stores the default configuration of the controller web.xml Includes all the required struts components

88 Resource Bundle Struts manage multilanguage needs is to use the standard Tag libraries Used to store application constants Example: text.customer.name=Name Predefined values for errors like: errors.header, errors.footer, errors.prefix, and errors.suffix Used for error messages Example: errors.required={0} is required. Located in /web-inf/classes

89 Resource Bundle To define the keys and the proper messages, you need an ApplicationResourceBundle For every language you want to support, a single ApplicationResources_xx_XX.properties file is required (where "xx_XX" stands for the specific locale; for example, en_US). In view, pass the attribute locale; otherwise, Struts does not look for the locale that the user's browser passes to the server via its request

90 Resource Bundle struts-config.xml web.xml action org.apache.struts.action.ActionServlet application ApplicationResources

91 struts-config.xml The primary Struts framework configuration and implementation configuration are contained in the stuts-config.xml file The power and flexibility of Struts is due to the extracting of configuration information from across the frame work. struts-config.xml may be given a different name Modular, easy to maintain, change application configuration without redeploying app

92 struts-config.xml Located in web-inf directory Outermost element is Two elements which describe actions: Contains form bean definitions Use element for each form bean Contains action definitions Use for each of action to be defined

93 Section Contains form bean definitions Use element for each form bean Attributes of element name: The name of the request or session level attribute that this form bean will be stored as A unique identifier for this bean, which will be used to reference it in corresponding action mappings type: The fully classified Java class name of form bean

94 Section Contains action definitions Action mapping determine navigation Use element for each of the actions Attributes of element path: Application context-relative path to the action type: Fully qualified Java class name of Action class name: Name of the element to use with the action

95 Section Other attributes: unknown: Set to true if this action should be configured as the default for this application, to handle all requests not handled by another action. Only one action can be defined as a default within a single application validate: Set to true, if the validate() method of the action associated with this mapping should be called Trigger automatic validation of form beans What to do if uncaught exception is thrown

96 Section Specifies data sources that application can use:

97 Global Forwards Remember RequestDispatcher.forward() method – hence the name forward!!! Logical name for all global filenames Addresses associated with common situations, so each action need not specify a specific address NO FILENAMES in execute() <forward name=“displayResults” path=“/pages/default.jsp”/>

98 Message Resources Designate the location of a properties file Properties in that file can then be output via

99 web.xml Includes all the required struts components Route request to the ActionServlet Is stored WEB-INF/web.xml

100 web.xml myApp action org.apache.struts.action.ActionServlet application ApplicationResources config /WEB-INF/struts-config.xml... 1

101 web.xml …………………….. action *.do

102 The Error Classes The Struts framework provides two classes to assist ActionError —This class is used to represent a single validation error ActionErrors —This class provides a place to store all the individual ActionError objects. As ActionError objects are created, simply stuff them into the ActionErrors holder and continue processing

103 The Error Classes The Hello World! application has been defined to have two different types of errors: basic data/form validation errors and business logic errors. The requirements for the two types are: Form validation Business Validation If the validate() method returns the ActionErrors object empty, Struts assumes there are no errors and processing moves to the Action class. If ActionErrors contains any ActionError elements, the user is redirected to the appropriate page to correct the errors

104 The Error Classes If processing is redirected for the user to correct the data entry, the ActionErrors object carries the individual ActionError elements back to the View for display. The View component can access the ActionErrors either directly or through the tag. Validation can be enabled or disabled on a page-by- page basis through settings in the Struts configuration file (struts-config.xml).

105 The ActionMapping Class The struts-config.xml determines what Action class the Controller calls The struts-config.xml configuration information is translated into a set of ActionMapping, which are put into container of ActionMappings Classes that end with s are containers The ActionMapping contains the knowledge of how a specific event maps to specific Actions

106 The ActionMapping Class The ActionServlet (Command) passes the ActionMapping to the Action class via the execute() method. This allows Action to access the information to control flow.

107 Fitting the Pieces The following basic ideas provide a quick view of the strengths of Struts: The Struts framework enables user to break the application functions into components quickly and easily A configuration file (struts-config.xml) enables user to assemble the application from components

108 Struts – Before & After A lot of complexity and layers have been added No more direct calls from the JSP file to the Service layer

109 What struts-blank.war provides Properties file with standard validator error messages However, properties file name does not match the message-resources name in struts-config.xml

110 Using Struts 1. Use WEB-INF/struts-config.xml to: 1. Designate Action classes to handle requests for blah.do 2. Specify URLs that apply in various situations 3. Declare any form beans that are being used 2. Create form bean to be populated by the form submission 3. Create other results beans

111 Using Struts 4. Create Action subclasses to handle requests 5. Create form that invokes blah.do 1. FORM ACTION="…/blah.do" …>… 6. Display results in JSP 1. Usually uses Struts bean or HTML tags 2. Sometimes uses JSTL or Struts looping/logic tags

112 Struts Flow

113 1. User select URL ending in.do ie: /myApp.do 2. Struts Action servlet receives control 3. URL is associated with an Action class The Action class is associated with a Form bean 4. The Form's reset method is called 5. Request parameters are mapped to the Form 6. The execute method on the Action class is called 7. An ActionForward is returned ie: /myApp.jsp

114 Creating Struts Application Step 1: Create entity beans Step 2: Create logic beans to manipulate entity beans Step 3: Create form bean with necessary properties You skip this step with DynaActionForm Step 4: Create Action class Extend Action or DispatchAction Step 5: Update struts-config.xml Define global forward, form, and action mappings Step 6: Create JSP page to support application

115 Hands On – Case Study 1 Components One simple result mapping No beans Illustrates Editing struts-config.xml Creating an Action Forms that invoke Actions Application organization

116 Hands On – Case Study 1 Step 1: Editing struts-config.xml 1. Make an action entry within action-mappings 1. path: URL pattern that should invoke the Action ".do" implied! You say /…/register1 but real pattern is /…/regsiter1.do 2. type: fully qualified class name of Action 3. scope: as in normal MVC (request, session, application) 4. name: bean name (use arbitrary name if no beans) 5. input: form that will trigger the Action

117 Hands On – Case Study 1 2. Create one or more forward entries within action 1. name: String that will be returned from the Action 2. path: address of associated JSP page 3. redirect: forward if false (default); redirect if true 3. Restart server struts-config.xml read only when application starts

118 Hands On – Case Study 1 struts-config.xml <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd"> <action path="/register1" type="training.RegisterAction1" name="noBean" scope="request" input="register1.jsp"> …

119 Hands On – Case Study 1 Step 2 & 3 1. Bean to be populated by form submission 1. Values automatically filled in based on correspondence between request parameter names and bean property names 2. Like or my BeanUtils.populateBean method 2. Results beans 1. Objects to hold results of business logic, data access logic, etc. 2. Just like the beans in normal MVC

120 Hands On – Case Study 1 Step 4: Create Action subclass 1. Add Struts-specific import statements import javax.servlet.http.*; import org.apache.struts.action.*; 2. Extend the Action class public class SomeAction extends Action { … } 3. Override the execute method public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { 4. Return mapping.findForward return(mapping.findForward("name-matching-entry-in-forward"));

121 Hands On – Case Study 1 package training; import javax.servlet.http.*; import org.apache.struts.action.*; public class RegisterAction1 extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { return(mapping.findForward("success")); }

122 Hands On – Case Study 1 Step 5: Create Form 1. ACTION should list …/register1.do 1. include the.do part, even though it is omitted in the struts-config.xml file 2. Relative URLs should be used 3. Struts-specific custom tags often used 1. Lets you associate a bean with the input elements 1.Make initial values come from database 2.Redisplay partially completed form

123 Hands On – Case Study 1 wipro_casestudy_1\register1.jsp New Account Registration New Account Registration Email address: Password:

124 Hands On – Case Study 1 Step 6: Display Results in JSP 1. System automatically forwards to appropriate page 1. By matching condition returned by the action to the name listed in the forward entry in struts-config.xml

125 Hands On – Case Study 1 wipro_casestudy_1\result1.jsp Success You have registered successfully. (Version 1)

126 Hands On – Case Study 1 Step 7: Compile Action class

127 Hands On – Case Study 1 Step 8: Access the page http:// :8080/wipro_case study_1/register1.jsp

128 Hands On – Case Study 2 Components Multiple result mappings No beans Illustrates Editing struts-config.xml Multiple forward entries within the action element Creating an Action Multiple mapping.findForward calls

129 Hands On – Case Study 2 Step 1: Editing struts-config.xml struts-config.xml <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts- config_1_1.dtd">

130 Hands On – Case Study 2 <action path="/register2" type="training.RegisterAction2" name="noBean" scope="request" input="register2.jsp"> …

131 Hands On – Case Study 2 Step 2 & 3 1. Bean to be populated by form submission 1. Values automatically filled in based on correspondence between request parameter names and bean property names 2. Like or my BeanUtils.populateBean method 2. Results beans 1. Objects to hold results of business logic, data access logic, etc. 2. Just like the beans in normal MVC

132 Hands On – Case Study 2 Step 4: Create Action subclass package training; import javax.servlet.http.*; import org.apache.struts.action.*; public class RegisterAction2 extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception

133 Hands On – Case Study 2 { String email = request.getParameter("email"); String password = request.getParameter("password"); if ((email == null) || (email.trim().length() < 3) || (email.indexOf("@") == -1)) { return(mapping.findForward("bad-address")); } else if ((password == null) ||(password.trim().length() < 6)) { return(mapping.findForward("bad-password")); } else { return(mapping.findForward("success")); }

134 Hands On – Case Study 2 Step 5: Create Form wipro_casestudy_2\register2.jsp New Account Registration New Account Registration Email address: Password:

135 Hands On – Case Study 2 Step 6: Display Results in JSP 1. System automatically forwards to appropriate page 1. By matching condition returned by the action to the name listed in the forward entry in struts-config.xml

136 Hands On – Case Study 2 Step 7: Compile Action class

137 Hands On – Case Study 2 Step 8: Access the page http:// :8080/wipro_case study_2/register2.jsp

138 Hands On – Case Study 3 Components Multiple result mappings Form bean to hold request data Result bean to hold computed data Illustrates Editing struts-config.xml form-bean declaration action name matching form-bean name Creating an Action Typecast of incoming form bean Creating and storing results beans

139 Hands On – Case Study 3 Step 1: Editing struts-config.xml struts-config.xml <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">

140 Hands On – Case Study 3 <action path="/register2" type="training.RegisterAction2" name="noBean" scope="request" input="register2.jsp"> …

141 Hands On – Case Study 3 Step 2: Create Form Bean to be auto populated 1. Must extend ActionForm 1. Argument to "execute" will be of type ActionForm 2. Cast value to your real type 3. ActionForm is in org.apache.struts.action package 4. Alternatively, DynaActionForm, can be used, which results in a Map of incoming names and values 2. Must have a zero argument constructor 1. System will automatically call this default constructor

142 Hands On – Case Study 3 3. Must have setXXX() methods 1. One method corresponding to each incoming request parameter that has to be inserted automatically 2. Request param names must match bean property names 4. Must have getXXX() methods 1. One method corresponding to each bean property which has to be displayed in JSP without Java syntax

143 Hands On – Case Study 3 UserFormBean.java package training; import org.apache.struts.action.*; public class UserFormBean extends ActionForm { private String email = "Missing address"; private String password = "Missing password"; public String getEmail() { return(email); } public void setEmail(String email) { this.email = email; } public String getPassword() { return(password); } public void setPassword(String password) { this.password = password;} }

144 Hands On – Case Study 3 Step 3: Create Result Beans These are the normal value objects used in MVC Do not need to extend any particular class Do not need zero argument constructors if JSP page will never create the objects Still need getter methods Setter methods are optional; you sometimes supply all needed values to the constructor Often returned by business-logic or data-access-logic code

145 Hands On – Case Study 3 SuggestionBean.java package training; public class SuggestionBean { private String email; private String password; public SuggestionBean(String email, String password) { this.email = email; this.password = password; } public String getEmail() { return(email); } public String getPassword() { return(password); }

146 Hands On – Case Study 3 Step 4: Create Action subclass package training; import javax.servlet.http.*; import org.apache.struts.action.*; public class RegisterAction3 extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception

147 Hands On – Case Study 3 { UserFormBean userBean = (UserFormBean)form; String email = userBean.getEmail(); String password = userBean.getPassword(); SuggestionBean suggestionBean = SuggestionUtils.getSuggestionBean(); request.setAttribute("suggestionBean", suggestionBean); if ((email == null) || (email.trim().length() < 3) || (email.indexOf("@") == -1)) { return(mapping.findForward("bad-address")); } else if ((password == null) || (password.trim().length() < 6)) { return(mapping.findForward("bad-password")); } else { return(mapping.findForward("success")); }

148 Hands On – Case Study 3 Step 5: Create Form wipro_casestudy_3\register3.jsp New Account Registration New Account Registration Email address: Password:

149 Hands On – Case Study 3 Step 6: Display Results in JSP Use Struts bean:write tag Most common approach bean:write automatically filters special HTML characters < replaced by < > replaced by >

150 Hands On – Case Study 3 bad_address3.jsp HTML> Illegal Email Address Illegal Email Address The address " is not of the form username@hostname (e.g., ). Please try again.

151 Hands On – Case Study 3 bad_pass3.jsp Illegal Password Illegal Password The password " “ is too short Here is a possible password:. Please try again.

152 Hands On – Case Study 3 result3.jsp Success You have registered successfully. Email Address: Password:

153 Hands On – Case Study 3 Step 7: Compile java classes

154 Hands On – Case Study 3 Step 8: Access the page http:// :8080/wipro_case study_3/register3.jsp

155 Hands On – Case Study 4 Components Application requirements Using the Model-View-Controller pattern to design a solution using Struts The View component: The HTML form and the form bean MessageResources and Application.properties files The Struts form bean: HelloForm.java Data validation and using ActionErrors The Controller component: HelloAction.java The Model component: HelloModel.java Passing data to the View using attributes: Constants.java Tying it all together: struts-config.xml

156 Hands On – Case Study 4 Illustrates Enable the user to enter a name to say Hello! to and output the string Hello !. Don't let the user submit the entry form without entering a name. If user does, provide an error message to help him fill the form out correctly.

157 Hands On – Case Study 4 Step 1: Create struts application structure copy blank.war to /webapps Rename to application start Tomcat Server

158 Hands On – Case Study 4 Step 2: The view component, HTML Form Use custom tags include tag libraries Pick up static text from properties file i18n & localization

159 Hands On – Case Study 4 Step 3: MessageResources & ApplicationResources.properties

160 Hands On – Case Study 4 Step 4: Form Bean On form submission, the data from form is populated into a java bean called form bean Has properties that match up with all the fields in the form must have getters & setters Form beans provide support for automatic data validation & resetting of bean property values validate() & reset() methods can be overridden as per requirement

161 Hands On – Case Study 4 Step 5: Data validation & ActionErrors The Hello World! application has been defined to have two different types of errors: basic data/form validation errors and business logic errors. The requirements for the two types are: Form validation—In the data entry form, make sure that the user doesn't submit the form with the person field empty Business logic—Enforce a rule that the user can't say hello to a person he isn't allowed to talk to. (Because Atilla the Hun has such a bad reputation, let's make him the person we won't speak to.)

162 Hands On – Case Study 4 Step 6: The Controller Component Action class

163 Hands On – Case Study 4 Step 7: The model component

164 Hands On – Case Study 4 Step 8: Passing data to the view using Attributes

165 Hands On – Case Study 4 Step 9: Tying it all together struts-config.xml

166 Hands On – Case Study 4 Step 10: Access the page http:// :8080/wipro_case study_4/hello.jsp

167 Struts Validator

168 Nature of Validations Client-side validations often implemented through JavaScript JavaScript may not be enabled/ may not be supported Front-end validations in business tier may affect performance Business level validations

169 Struts Validator – To Rescue Using the Jakarta Commons Validator [ASF, Validator] brings several consequences: The Validator is a framework component that meets client side validation & server-side validation requirements configured from an XML file that generates validation rules for the fields in the form Rules are defined by a Validator that is also configured through XML Validators for basic types, like dates and integers, are provided. If needed, it can be created Regular expressions can be used for pattern-based validations such as postal codes and phone numbers Localized validations are supported

170 Validation Technique before Struts1.1 Two options for Form Validation: ActionForm class -- for simple/syntax validation Action class – business validation On validation errors: ActionErrors object is returned Technique is still valid in 1.1

171 Benefits Optimal use of resources: JavaScript validations are provided when enabled, and server-side validations are guaranteed A single point of maintenance: Both client-side and server-side validations are generated from the same configuration Extendibility: Custom validations can be defined as regular expressions or in Java code Maintainability: It is loosely coupled to the application and can be maintained without changing markup or code

172 Benefits The Struts ActionForm can simply extend the ValidatorForm or ValidatorActionForm class. The rest is automatic. Easy deployment of client-side validation: To make use of the client-side validations, just add a single JSP tag to generate the validation script and use that script to submit the form Easy configuration: The Validator uses an XML file for configuration, just like the web application deployment descriptor and the Struts configuration

173 Benefits Localization: Localized validations can be defined only when and where they are needed Integration with Struts: By default, validations share the Struts message bundle Localized text can be centralized and reused Easy deployment of server-side validation: To make use of the server-side validations,

174 Shortcomings Nonmodal client-side validations The generated JavaScript is nonmodal; it does not engage until the form is submitted Dependencies The validations are detached from the fields and from the ActionForm properties. The page markup, the ActionForm, and the Validator and Struts configuration files must all be synchronized

175 Overview -- Pieces that make up Struts Validator Component Validators -- Validator-Rules.xml Resource Bundle -- ApplicationResources.properties XML Configuration File -- Validation.xml JSP Tag ValidatorForm ValidatorActionForm

176 Validator Configuration File Struts Validator can actually use two XML files: one to set up the validators -- Validator-rules.xml another with the settings for the applications – Validation.xml NOTE: Struts 1.0 uses a single configuration file Strength: validations are declared outside the application source code using an XML configuration file The configuration specifies which fields on a form need validation, the validators a field uses, and any special settings to be used with a field.

177 Validator Configuration File Strength Alternate formsets can be configured for different locales and override any locale- sensitive validations All of the validators used by the framework are configured through XML, including the basic validators that ship with the package Option for custom Validators This makes for a very flexible package

178 Validator Configuration File In Struts 1.1, the paths to the Validator configuration files are declared in the struts- config.xml file: <plug-in className="org.apache.struts.validator.ValidatorPlugIn"> <set-property property="pathnames“ value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>

179 Validator-rules.xml Includes validators for : basic validators native types and other common needs, like e-mail and credit card validations Declare required validators Validator elements are defined in two parts: A Java class and method for the server-side validation JavaScript for the client-side validation Location web-inf

180 Validator-rules.xml ValidatorPurpose requiredSucceeds if the field contains any characters other than whitespace. mask Succeeds if the value matches the regular expression given by the mask attribute. range Succeeds if the value is within the values given by the min and max attributes ((value >= min) & (value <= max)). maxLength Succeeds if the field’s length is less than or equal to the max attribute. minLength Succeeds if the field’s length is greater than or equal to the min attribute.

181 Validator-rules.xml ValidatorPurpose byte, short, integer, long, float, double Succeeds if the value can be converted to the corresponding primitive. date Succeeds if the value represents a valid date. A date pattern may be provided. creditCardSucceeds if the value could be a valid credit card number. emailSucceeds if the value could be a valid e-mail address.

182 Validation.xml A formset is a wrapper for one or more forms Contains validations for entire application Each form element is given its own name correspond to either the form bean name or the action path from Struts configuration Each form element is composed of a number of field elements. The field elements designate which validator(s) to use with the depends attribute The optional msg element lets you specify a custom message key for a validator and the message key to use for any replacement parameters The arg0 element specifies the first replacement parameter to use with any messages that need them The var element is used to pass variable properties to the validator Can be localized

183 ApplicationResources.properties On validation failure, it passes back a message key and replacement parameters Entry for our required validator looks like: errors.required={0} is required. When a field is configured to use the required validator, the field’s label is also passed as a replaceable parameter The validator can then reuse the same message for all the required fields Alternatively, customized messages can be defined to selectively override the defaults

184 JSP Tag Import the validator taglib This section calls the validation script. Then, the form is submitted <html:form action="/logonSubmit" focus="username" onsubmit="validateLogonForm(this)"> Add the tag to output the JavaScript anywhere on the page

185 ValidatorForm & ValidatorActionForm To enable the Struts Validator for Struts 1.1 extend FormBean from ValidatorForm OR ValidatorActionForm The ValidatorForm will match the formset name with the form- bean name The ValidatorActionForm will match the formset name with the actionmapping path In most cases, the Struts Validator can completely replace the need to write a custom validate method for an ActionForm First, call the ancestor validate method Validator framework is invoked public ActionErrors validate(ActionMapping mapping,HttpServletRequest request) { // b ActionErrors errors = super.validate(mapping, request);}

186 ValidatorForm & ValidatorActionForm To run our own validations Implement validate() method public ActionErrors validate(ActionMapping mapping,HttpServletRequest request) { // b ActionErrors errors = super.validate(mapping, request); //continue validating }

187 The validate() method Extend form bean from ValidatorForm instead of ActionForm public final class LogonForm extends org.apache.struts.validator.action.ValidatorForm {} When the controller calls the validate method, the ValidatorForm method will kick in and follow the rules we defined in the validation.xml file ActionErrors errors = super.validate(mapping, request); if (errors == null) errors = new ActionErrors();

188 Hands On Implement Struts Validator http://wiki.apache.org/jakarta- commons/ValidatorSetup

189 Adding struts to an existing web-app Copy struts_install_dir/lib/*.tld Place in theWEB-INF directory of your Web application Copy struts_install_dir/lib/*.jar Place in the WEB-INF/lib directory of your Web application Also include struts.jar in your development CLASSPATH Modify WEB-INF/web.xml Use servlet and servlet-mapping entries so that URLs that end in *.do are mapped to org.apache.struts.action.ActionServlet Create struts-config.xml Define mappings for specific URLs to specific actions

190 Best Practices The Action should not perform any business logic. (Action is part of the controller) The ActionForm should not be used as the data model The ActionForm should not be used to validate business objects

191 Tips Always start at.do – never show.jsp Use some JavaScript to submit forms onClick() or onChange() Don't bother with /do/myAction notation When back buttons and refresh won't work Place forms in session scope with nocache="true" Always redirect to a get before presenting page (use xxx.do?action="refresh") This is an all or nothing solution that could impact performance due to memory utilization

192 Common Errors Check boxes are not set Use reset method in form to set check box properties to false Session timeouts cause null pointer exceptions Use lazy lists in forms with factory Properties not set on form Verify type is correct Make sure form values start with lower case and each separator (.) has a getter

193 Common Errors Button does not call proper method Use JavaScript if necessary to set action for buttons Action class is not being called on submit Verify action path in struts-config matches the form action name Remove validate="true" from struts-config and call form.validate directly from action When chaining actions form properties are lost The reset() action is called between actions so add properties to the request string

194 Chaining Actions Used when more than one action will process a single request Challenges: Different actions will have different forms – input may not match up Setting return point is difficult Solutions: Avoid chaining actions Start with a clean slate each time – use redirect Store return point in session

195 Features Built in exception handling at an action an global scope are specified in the config file. I18N, Internationalization, support with resource bundles. JSP custom tags Validator framework from the jakarta.commons project; this is set up as a plugin and configured via validation.xml and validation-rules.xml Tiles – a templating mechanism incorporated into Struts for managing page layout. Supports database access classes.

196 ForwardAction ForwardAction is the one of the most frequently used built-in Action classes. The primary reason behind this is that ForwardAction allows you to adhere to MVC paradigm when designing JSP navigation. Most of the times you will perform some processing when you navigate from one page to another. In Struts, this processing is encapsulated in the Action instances. There are times however when all you want to do is navigate from one page to another without performing any processing. You would be tempted to add a hyperlink on the first page for direct navigation to the second. Watch out! In Model 2 paradigm, a straight JSP invocation from another JSP is discouraged, although not prohibited.

197 To configure the use of this Action in your struts-config.xml file, create an entry like this:

198 DispatchAction DispatchAction is one of the Struts built-in action that provides a mechanism that facilitates having a set of related functionality in a single action instead of creating separate independent actions for each function. public abstract class DispatchActionextends BaseActionBaseAction

199 To configure the use of this action in your struts-config.xml file, create an entry like this: which will use the value of the request parameter named "method" to pick the appropriate "execute" method, which must have the same signature (other than method name) of the standard Action.execute method. For example, you might have the following three methods in the same action: public ActionForward delete(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception public ActionForward insert(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception public ActionForward update(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception and call one of the methods with a URL like this: http://localhost:8080/myapp/saveSubscription.do?method=update

200 public abstract class LookupDispatchAction extends DispatchAction DispatchAction An abstract Action that dispatches to the subclass mapped execute method. This is useful in cases where an HTML form has multiple submit buttons with the same name. The button name is specified by the parameterproperty of the corresponding ActionMapping. To configure the use of this action in your struts-config.xml file, create an entry like this:

201 Your subclass must implement both getKeyMethodMap and the methods defined in the map. An example of such implementations are: protected Map getKeyMethodMap() { Map map = new HashMap(); map.put("button.add", "add"); map.put("button.delete", "delete"); return map; }

202 LookupDispatchAction VS. DispatchAction We will perform following changes to the application to make it work with LoopupDispatchAction: Our action class (InvitationAction.java) will extend LoopupDispatchAction instead of DispatchAction. Add a application properties file that will contain the detail of the method to be executed when a particular value will come from the request parameter which is defined in attribute parameter in action tag. Some basic changes to jsp for making the ui more perfect.


Download ppt "Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla."

Similar presentations


Ads by Google