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

Slides:



Advertisements
Similar presentations
Web Development with Karsten Schulz Terp-Nielsen Master Principal Sales Consultant Oracle Denmark.
Advertisements

Apache Struts Technology
JSP1 Java Server Pages (JSP) Introducing JavaServer Pages TM (JSP TM ) JSP scripting elements.
 Copyright Wipro Technologies JSP Ver 1.0 Page 1 Talent Transformation Java Server Pages.
MVC Frameworks Alternatives to coding the MVC pattern.
Struts1 Apache Struts Dr Jim Briggs. Struts2 What is Struts? Struts is an open source framework for building Java web applications Supports MVC/Model.
Object-Oriented Enterprise Application Development Tomcat 3.2 Configuration Last Updated: 03/30/2001.
Struts Basics SSE USTC Qing Ding. Agenda What is and Why Struts? Struts architecture – Controller: Focus of this presentation – Model – View Struts tag.
DT211/3 Internet Application Development
18-Jun-15 JSP Java Server Pages Reference: Tutorial/Servlet-Tutorial-JSP.html.
Objectives:1. Investigate the Web application deployment descriptor 2. Install and deploy Tomcat and struts 3. Design and deploy a struts application Struts.
Q: According to Intel, the Pentium conforms to the IEEE standards 754 and 854 for floating point arithmetic. If you fly in aircraft designed using a Pentium,
Apache Struts Technology A MVC Framework for Java Web Applications.
Introduction to Java web programming Dr Jim Briggs JWP intro1.
1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external.
Struts 2.0 an Overview ( )
UNIT-V The MVC architecture and Struts Framework.
Introduction to the Jakarta Struts Framework  The Topics: JavaServer Pages (JSP) Overview JSP Tags and Tag Libraries Overview Model – View – Controller.
Form Handling, Validation and Functions. Form Handling Forms are a graphical user interfaces (GUIs) that enables the interaction between users and servers.
Overview of JSP Technology. The need of JSP With servlets, it is easy to – Read form data – Read HTTP request headers – Set HTTP status codes and response.
DAT602 Database Application Development Lecture 15 Java Server Pages Part 1.
1 CIS336 Website design, implementation and management (also Semester 2 of CIS219, CIS221 and IT226) Lecture 9 JavaServer Pages (JSP) (Based on Møller.
Netbeans – jsp.zip Introduction to JSP Netbeans – jsp.zip.
M. Taimoor Khan * Java Server Pages (JSP) is a server-side programming technology that enables the creation of dynamic,
FALL 2005CSI 4118 – UNIVERSITY OF OTTAWA1 Part 4 Web technologies: HTTP, CGI, PHP,Java applets)
Architecture Of ASP.NET. What is ASP?  Server-side scripting technology.  Files containing HTML and scripting code.  Access via HTTP requests.  Scripting.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
Author: DoanNX Version 2.0/Time: 30’. The ways to solve it There are 2 main ways:  Client-side: Using JavaScript (now one very good option is JQuery).
Using JavaBeans and Custom Tags in JSP Lesson 3B / Slide 1 of 37 J2EE Web Components Pre-assessment Questions 1.The _____________ attribute of a JSP page.
CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Environment.
JSP Java Server Pages Softsmith Infotech.
Design Patterns Phil Smith 28 th November Design Patterns There are many ways to produce content via Servlets and JSPs Understanding the good, the.
Introduction to JavaServer Pages (JSP) Slides from Dr. Mark Llewellyn.
Java Server Pages Lecture July Java Server Pages Java Server Pages (JSPs) provide a way to separate the generation of dynamic content (java)
Jakarta Struts Presented by Object Computing, Inc. (OCI) Written by Greg Elliott
JSP Architecture Outline  Model 1 Architecture  Model 2 Architecture.
JAVA SERVER PAGES. 2 SERVLETS The purpose of a servlet is to create a Web page in response to a client request Servlets are written in Java, with a little.
Struts J2EE web application framework “ Model 2 ” Model View Controller Controller Servlet Key features XML metadata Struts taglib Simplified form validation.
Lecturer: Prof. Piero Fraternali, Teaching Assistant: Alessandro Bozzon, Advanced Web Technologies: Struts–
JAVA SERVER PAGES CREATING DYNAMIC WEB PAGES USING JAVA James Faeldon CS 119 Enterprise Systems Programming.
Chapter 3 Servlet Basics. 1.Recall the Servlet Role 2.Basic Servlet Structure 3.A simple servlet that generates plain text 4.A servlet that generates.
Extending HTML CPSC 120 Principles of Computer Science April 9, 2012.
JSTL Lec Umair©2006, All rights reserved JSTL (ni) Acronym of  JavaServer Pages Standard Tag Library JSTL (like JSP) is a specification, not an.
Java server pages. A JSP file basically contains HTML, but with embedded JSP tags with snippets of Java code inside them. A JSP file basically contains.
Copyright © 2002 ProsoftTraining. All rights reserved. JavaServer Pages.
Struts Framework Anna Paščenko. What is Struts?  An open source framework for building Java web applications.
J2EE Struts 1 3 Struts: Introduction 1 4 Once you’ve coded a lot of JSP applications, you find yourself doing a lot of repetitive things. Also,
JSP BASICS AND ARCHITECTURE. Goals of JSP Simplify Creation of dynamic pages. Separate Dynamic and Static content.
CS562 Advanced Java and Internet Application Introduction to the Computer Warehouse Web Application. Java Server Pages (JSP) Technology. By Team Alpha.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 JSP Application Models.
Basic JSP Celsina Bignoli Problems with Servlets Servlets contain –request processing, –business logic –response generation all lumped.
©SoftMooreSlide 1 Introduction to HTML: Forms ©SoftMooreSlide 2 Forms Forms provide a simple mechanism for collecting user data and submitting it to.
Preface IIntroduction Objectives I-2 Course Overview I-3 1Oracle Application Development Framework Objectives 1-2 J2EE Platform 1-3 Benefits of the J2EE.
13 Copyright © 2004, Oracle. All rights reserved. Adding Validation and Error Handling.
11 Copyright © 2004, Oracle. All rights reserved. Customizing Actions.
Struts Framework Day-2 Ashok Chakravarti. DataSource Usage Sample Struts-config.xml …
Implementation Struts Framework for well-architectured web applications Model-View-Controller design pattern.
1 Java Server Pages A Java Server Page is a file consisting of HTML or XML markup into which special tags and code blocks are inserted When the page is.
Java Programming: Advanced Topics 1 Building Web Applications Chapter 13.
Java Server Pages. 2 Servlets The purpose of a servlet is to create a Web page in response to a client request Servlets are written in Java, with a little.
Bayu Priyambadha, S.Kom. Static content  Web Server delivers contents of a file (html) 1. Browser sends request to Web Server 3. Web Server sends HTML.
10 Copyright © 2004, Oracle. All rights reserved. Building ADF View Components.
APACHE STRUTS ASHISH SINGH TOMAR ast2124. OUTLINE Introduction The Model-View-Controller Design Pattern Struts’ implementation of the MVC Pattern Additional.
Apache Struts Technology A MVC Framework for Java Web Applications.
V Web Tier Architecture MVC and Struts. v First, there were servlets And things were good Faster than CGI programs More scalable with built-in.
Struts 2 Development. Topics  Roles in Struts Development  Control Flow  Actions  Struts 2 Views and Target  Struts 2 Custom Tags  Validation 
Java Servlets.
Knowledge Byte In this section, you will learn about:
Unit 6-Chapter 2 Struts.
The Model Layer What is Model?
Presentation transcript:

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

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

Struts Overview

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

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

Drawbacks of JSP

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.

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

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.

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

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

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

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.

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.

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.

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

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

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

Struts – Schematic Overview

RELY-ON SOLUTIONS Core Struts Classes

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

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

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

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

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

Components

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.

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.

Struts Controller

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

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.

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.

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.

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;

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.

Action Class

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.

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.

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.

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

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.

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.

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.

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

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.

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.

Struts Model Components

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

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

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

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

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

Struts View Components

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

Tag Libraries

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

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

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

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

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

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

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

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

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

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

Form tags Generates HTML:

Generates:

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

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

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

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

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

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; }

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

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

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

Struts Controller Components

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

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

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

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 {

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.

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.

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

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

Struts Configuration

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

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

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

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

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

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

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

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

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

Section Specifies data sources that application can use:

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”/>

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

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

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

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

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

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

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

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

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.

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

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

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

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

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

Struts Flow

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

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

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

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

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

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

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

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

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")); }

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

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

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

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

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

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

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

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" " config_1_1.dtd">

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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 >

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

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.

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

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

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

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

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.

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

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

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

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

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

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

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

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

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

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

Struts Validator

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

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

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

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

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

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,

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

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

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.

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

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"/>

Validator-rules.xml Includes validators for : basic validators native types and other common needs, like 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

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.

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. Succeeds if the value could be a valid address.

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

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

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

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);}

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 }

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

Hands On Implement Struts Validator commons/ValidatorSetup

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

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

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

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

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

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

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.

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.

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

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

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:

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:

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; }

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.