Struts Module Version 1

download Struts Module Version 1

of 82

Transcript of Struts Module Version 1

  • 8/3/2019 Struts Module Version 1

    1/82

    Jakarta Struts

    K.Srivatsan

  • 8/3/2019 Struts Module Version 1

    2/82

    Introduction to Struts

    Its is an open source Web application framework developed as ApacheJakarta project

    http://jakarta.apache.org/struts/

    Created by Craig R. McClanahan and then donated to the Jakarta project

    In June of 2001, Struts 1.0 was released.

    Support for Struts comes in three forms. First is the API documentation that comes with Struts.

    Second, Struts has a very active mailing list where you can get support forvirtually any question.

    Third, several third-party consulting companies specialize in Struts support anddevelopment.

  • 8/3/2019 Struts Module Version 1

    3/82

    Framework

    A framework is a set of classes which handles the flow necessary toperform a complex task.

    It requires plug-in classes specific to the application and can also allow

    additional plug-in classes to extend functionality.

    A framework follows the "don't call us, we'll call you" idiom.

    The framework calls the code to accomplish what needs to be done.

    An AP I is a collection of routines,objects,modules etc that the application code

    can link to and call to accomplish a task.

    The AP I is totally distinct from the implementation.

    a number of implementation of the servlet API,

  • 8/3/2019 Struts Module Version 1

    4/82

    Characteristics of Framework

    Build applications faster as a result of similar structures.

    Easier to maintain, and more consistent to their users.

    Lose some creative freedom

    Any substantive change to the framework's design would reduce its benefitsconsiderably,

    The framework's defines an architecture for the application.

  • 8/3/2019 Struts Module Version 1

    5/82

    What is Struts?

    Model-View-Controller (MVC) framework

    Used for constructing web applications using Servlets and JSPs

    Application can run on any Servlet container including J2EE compliant Appservers

    It is Pattern oriented

    MVC, Front Controller

    Includes JSP custom tag libraries

  • 8/3/2019 Struts Module Version 1

    6/82

    Why Struts?

    Encourages good design practice and modeling

    Open source

    Integrates well with J2EE

    Good taglib support

    Works with existing web apps

    Unified error handling programmatically and declaratively

  • 8/3/2019 Struts Module Version 1

    7/82

    MVC - Model 1 & 2

    MODEL - I

    MODEL - 2

  • 8/3/2019 Struts Module Version 1

    8/82

    Struts: MVC-based Architecture

    Controller mediates application flow and delegates to appropriate handler called Action

    Action Handlers

    use model components

    Model encapsulates business logic or state

    Control forwarded back

    through the Controller to the appropriate View

    The forwarding can be determined

    consulting a set of mappings in configuration file

    A loose coupling between the View and Model

  • 8/3/2019 Struts Module Version 1

    9/82

    Struts MVC Pattern

  • 8/3/2019 Struts Module Version 1

    10/82

    The Controller

    Is the switch board of MVC architecture , requests goes through thecontroller

    Responsible for flow control (action mapping) of the request handling reads

    configuration file to determine the flow control

    Struts framework provides a built-in base servlet

    org.apache.struts.action.ActionServlet

    Servlet mapping has to be configured in web.xml

    Struts related configuration is done through struts-config.xml

    Action Mapping defines the mapping between request URI of incoming

    requests to specific Action class

  • 8/3/2019 Struts Module Version 1

    11/82

    ActionServlet

    Performs the role of Controller Process user requests

    Determine what the user is trying to achieve according to the request

    Pull data from the model (if necessary) to be given to the appropriate view,

    and Select the proper view to respond to the user

    Delegates work to Action classes

    Is responsible for initialization and clean-up of resources

    Loads the application configuration corresponding to the init-param's in

    web.xml

  • 8/3/2019 Struts Module Version 1

    12/82

    Configuration file

    Configuration file contains action mappings URL to Action mappings

    Controller uses these mappings to turn HTTP requests into application

    actions

    Determines forwarding/navigation

    Mapping must specify

    A request path

    Action to act upon the request

  • 8/3/2019 Struts Module Version 1

    13/82

    Struts-Config File

    Struts controller ActionServlet needs to know several things about how each request

    URI should be mapped to an appropriate Action class

    These requirements are encapsulated in a Java interface named ActionMappings

    Struts framework creates Action Mapping object from

    It also Contains definition of Form Beans used

    contains FormBean definitions

    contains action definitions

    element for each action defined

  • 8/3/2019 Struts Module Version 1

    14/82

    struts-config.xml- Form bean

    Its a Java class extending the ActionForm class) for the input form

    Defined in struts-config.xml file

    Contains only property getter and property setter methods for each field-no business

    logic

    Provides standard validation mechanism, has Two Attributes

    name:

    The name of the request (and session level attribute that this form bean will be stored as

    type:

    The fully-qualified Java class name of form bean

  • 8/3/2019 Struts Module Version 1

    15/82

    Each element requires the following attributes to be defined:

    path: The application context-relative path to the action (URI of the request)

    type: The fully qualified java classname of Action class

    name: The name of element to use with this action

    input: The name of the display page when input form validation error condition

    occurs

    scope: The scope in which form bean is created

    validate: Whether to perform input form validation or not

  • 8/3/2019 Struts Module Version 1

    16/82

    struts-config.xml

  • 8/3/2019 Struts Module Version 1

    17/82

    ActionForm Bean & Controller

    For each ActionForm bean defined in struts-config.xml file, ActionServlet

    Check session scope for an instance of ActionForm bean

    If it does not exist, controller creates one

    Call corresponding setter method of ActionForm bean for every request

    parameter whose name corresponds to the name of a property of the bean

    Pass the updated ActionForm bean object as a parameter to execute()

    method of Action class

  • 8/3/2019 Struts Module Version 1

    18/82

    Writing ActionForm Bean

    Add just getter and setter methods for each property of a input form

    Do not include any business logic code

    Add a standard validation method called validate()

    Controller will call this validation

    Define a property (with associated getXxx and setXxx methods) for eachfield that is present in the input form

  • 8/3/2019 Struts Module Version 1

    19/82

    ActionClass

    Focus on control flow

    Process client request by calling other objects (BusinessLogic beans) inside its

    execute() method

    Returns an ActionForward object that identifies a destination resource to

    which control should be forwarded to

    The destination resource could be

    JSP

    Tile definition

    Velocity template

    Another Action

  • 8/3/2019 Struts Module Version 1

    20/82

    The ActionClass

    Java class that extends org.jakarta.struts.action.Action that does the work

    of the application Handle business logic by itself

    Delegate business logic to Model components

    Override execute(..) method of Action class -invoked by controller

    public ActionForward execute(

    ActionMapping mapping,

    ActionForm form,

    HttpServletRequest request,

    HttpServletResponse response)

    throws Exception;

    Return an appropriate ActionForward object

  • 8/3/2019 Struts Module Version 1

    21/82

    View Components

    JSP files which you write for your specific application Set of JSP custom tag libraries

    Resource files for internationalization

    Allows for fast creation of forms for an application

    Works in concert with the controller Servlet

    With just JSP, you have to do

  • 8/3/2019 Struts Module Version 1

    22/82

    View

    ActionForward object tells Servlet controller which JSP page is to bedispatched to

    JSP pages use ActionForm beans to get output Model data to display

    Struts contains a series of tag libraries

    Facilitates communication between HTML designers and developers

    Facilitates dynamic Web content

  • 8/3/2019 Struts Module Version 1

    23/82

    web.xml

    Has to have deployment descriptor that includes:

    Configure ActionServlet instance and mapping

    struts-config.xml file as

    Define the Struts tag libraries

    Server initializes this servlet when Server starts up.

    The content of this element must be a positive integer indicating the

    order in which the servlet should be loaded.

    Lower integers are loaded before higher integers.

  • 8/3/2019 Struts Module Version 1

    24/82

    Example: web.xml

    action org.apache.struts.action.ActionServlet config /WEB-INF/struts-config.xml

  • 8/3/2019 Struts Module Version 1

    25/82

    Struts Flow

  • 8/3/2019 Struts Module Version 1

    26/82

    Application Walk-through

    Welcome To Validation

    Welcome Struts Guide

    My First Struts Example

  • 8/3/2019 Struts Module Version 1

    27/82

    Insurance.jsp

    name

    address

    phone

    pincode

  • 8/3/2019 Struts Module Version 1

    28/82

    The Formpublic class InsuranceForm extends ActionForm {

    private String address;

    private double phone;private String name;

    private double pincode;

    public String getAddress() {

    return address;

    public void setAddress(String a) {

    this.address = a; }

    public double getPhone() {

    return phone;}

    public void setPhone(double p) {

    this.phone = p; }

    public String getName() {

    return name; }

    public void setName(String n) {

    this.name = n;

    }

    public double getPincode() {

    return pincode;

    }

    public void setPincode(double p) {

    this.pincode = p;

    } }

  • 8/3/2019 Struts Module Version 1

    29/82

    Action Class

    import com.training.InsuranceForm;

    public class Action extends org.apache.struts.action.Action {

    public ActionForward execute(

    ActionMapping mapping,

    ActionForm form,

    HttpServletRequest request,

    HttpServletResponse response)

    throws Exception {try {

    ActionForward forward = new ActionForward();

    InsuranceForm insuranceForm = (InsuranceForm) form;

    ModelData md = new ModelData();

    insuranceForm = md.getData(insuranceForm);

    } catch (Exception e) { System.out.println(e);}

    return(mapping.findForward("success"));

    }

    }

  • 8/3/2019 Struts Module Version 1

    30/82

    Model Data

    package com.training;

    public class ModelData {

    public InsuranceForm getData(InsuranceForm frm)

    {

    frm.setAddress(frm.getAddress().toUpperCase());

    frm.setPhone(frm.getPhone());

    frm.setPincode(frm.getPincode());

    frm.setName(frm.getName().toUpperCase());

    returnfrm;

    }

    }

  • 8/3/2019 Struts Module Version 1

    31/82

    Success.jsp

    Success.jsp

    Thanks For Registering you have given the following information

    Demo 1.2

  • 8/3/2019 Struts Module Version 1

    32/82

    Validation

    Perform simple, prima facia validations

    using the ActionForm validate() method , an optional one

    Handle the "business logic" validation in the Action class

  • 8/3/2019 Struts Module Version 1

    33/82

    Validate Method

    public ActionErrors validate(

    ActionMapping mapping,

    HttpServletRequest request) {

    ActionErrors errors = new ActionErrors();

    if ((username == null) || (phone.length() == 0)) {

    errors.add("err_order",

    new org.apache.struts.action.ActionError

    ("error.field.required"));

    }

    return errors;

    }

  • 8/3/2019 Struts Module Version 1

    34/82

    Application Errors in Action Class

    Create ActionErrors object and return

    ActionServlet can take action if a certain exception is thrown

    Can be global or Action-based

    Can either be a simple forward, or passed to a custom error handlerclass through default ExceptionHandler

  • 8/3/2019 Struts Module Version 1

    35/82

    Message Resources

    The message resources section declares the location of properties file that

    stores the key/value pairs of your application.

    If a message is used in several places, it can be updated with a singlechange.

    This is consistent with the Struts philosophy of making as many changes as

    possible in config files, not in Java or JSP code.

    if you use messages pervasively in your JSP pages, you caninternationalize your application by having multiple properties filescorresponding to the locale, as with standard I18N in Java

    MessageResources.properties

    MessageResources_jp.properties

    MessageResources_es.properties

    MessageResources_es_mx.properties

  • 8/3/2019 Struts Module Version 1

    36/82

    Advantages ofProperties Files

    form.title=Registration

    form.firstName=First name

    :

    The main attribute of the tag is the parameter attribute, which gives the location of theproperties file for your application relative to the \WEB-INF\classes\ directory of yourwebapp.

    In the declaration, the .properties extension is implied.

  • 8/3/2019 Struts Module Version 1

    37/82

    Parameterized Messages

    Properties File

    error.missing=You must enter {0}, you are not authorised

    error.number={0} and {1} are not whole numbers!

    JSP Pages

  • 8/3/2019 Struts Module Version 1

    38/82

    Message Resources

    Using the struts-config.xml file to configure your message resources is

    preferred than in web.xml

    Multiple message-resources tags could be used to load messages frommultiple files.

    The key attribute to give a unique name to each bundle.

  • 8/3/2019 Struts Module Version 1

    39/82

    Tag Libraries 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 scriptlets

    Template tags (Tiles in v1.1)

    Tags to form JSP templates that include parameterized content

    Nested Tags (v1.1)

    Allows for object hierarchy Helpful for rendering lists of lists

  • 8/3/2019 Struts Module Version 1

    40/82

    Access toTag Libraries

    All tag libraries are defined in web.xml using element

    /WEB-INF/struts-bean.tld

    /WEB-INF/struts-bean.tld

    /WEB-INF/struts-html.tld

    /WEB-INF/struts-html.tld

  • 8/3/2019 Struts Module Version 1

    41/82

    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

  • 8/3/2019 Struts Module Version 1

    42/82

    Start the page with this tag , it creates an html element .

    The Attributes are

    Locale : Set to true to store a locale in the session based on the currentrequests accept language header

  • 8/3/2019 Struts Module Version 1

    43/82

    The form Tag

    Tag is used render a standard HTML form tag and to link the HTML form

    with an ActionForm configured for the application.

    Each field in the HTML form should correspond to a property of theActionForm.

    When an HTML field name and a property name match, the property fromthe ActionForm is used to populate the HTML field.

    When the HTML form is submitted, the framework will store the user's inputinto the ActionForm, again matching up the HTML field names to theproperty names.

  • 8/3/2019 Struts Module Version 1

    44/82

    To work with html forms , enclose the fields within this tag

    The Attributes are

    Action : the url to which this form is submitted

    Focus : the field names to which initial focus will be assigned with a javascript function

    Method : Default is post

    Onsubmit : javascript event handler

    Creates the submit button

    The value for the action attribute is used to select the ActionMapping the page isassumed to be processing,

    If extension mapping is being used (*.do), the action value should be equal to thevalue of the path attribute of the corresponding action element, optionally followed bythe correct extension suffix.

  • 8/3/2019 Struts Module Version 1

    45/82

    : Creates text field

    This tag displays error messages as returned by your in the input page

    Prroperty , the name of the property for which error message is stored

    Error.header : Header text for error message

    Error .footer : the footer for error message

    Erros.prefix : text to be added before each message

    Errors.suffix text that will be added after each error in the list

  • 8/3/2019 Struts Module Version 1

    46/82

    Creates a Text Area

    To create check box

    clickme Attribute

    Value : the value to be transmitted if the check box is clicked when the form issubmitted,by default the value of on will be returned.

    ToCreate radio button

    red

  • 8/3/2019 Struts Module Version 1

    47/82

    Creates a Button with tag , can be connected to javascript funtions

    using html button tag

    function clicker()

    {

    confirm(you clicked the button);

    }

  • 8/3/2019 Struts Module Version 1

    48/82

    This tag creates a HTML tag,the base url for this hyperlink is calcuated

    based on the attribute.

    Forward : use the value of this attribute as the name of the global actionforward

    Action : use the value of this attribute as the name of an action

    Href: use the value of this attribute

    Page : generate a server relative uri including the context path andapplication prefix

    register

  • 8/3/2019 Struts Module Version 1

    49/82

    and tags create controls and

    elements , used to create scrollable list or drop down list boxes.

    Mutiple1

    : check box group

  • 8/3/2019 Struts Module Version 1

    50/82

    Handling property in Form Bean

    String[] mulibox = new String[5];

    public String[] getMultiBox()

    {

    return multibox ;

    }

    public setMultiBox(String[] multiBox)

    {

    this.multibox = multibox;

    }

  • 8/3/2019 Struts Module Version 1

    51/82

    Example HTML Tag



    Male Female

    Age: " " 0-19 20-49

  • 8/3/2019 Struts Module Version 1

    52/82

    Logic Tags

    The Logic tag library contains tags that are useful for managing conditional

    generation of output text, looping over object collections for repetitivegeneration of output text, and application flow management.

    The tags within the Logic tag library are into four separate categories

    Value comparison

    Substring matching Redirecting and forwarding

    Collection utilities

  • 8/3/2019 Struts Module Version 1

    53/82

    Logic Tag Sample

    It represents the body content of this tag for every element of a collection , whichmust be an Iterator a collection or an array


    If we use custom tag that return an array of values Iterate tag can be used

  • 8/3/2019 Struts Module Version 1

    54/82

    Bean Tag Sample

    Tags for accessing beans and their properties

    Used to access data Creating Beans

    Define a scripting variable (named by id) based on the value of abean property

    Retrieving Value

    Retrieves the value of the specified bean property and renders it to the pageoutput as a String.

    Hello

  • 8/3/2019 Struts Module Version 1

    55/82

    DynaForm

    ActionForms increases the number of classes to a project.

    Properties need to be defined in the ActionForm to be able to capture datafrom the HTML form.

    If a property is added or removed from the HTML form, the ActionFormclass may need to be modified and recompiled.

    There is a dynamic form avoids having to create a concrete ActionFormclasse

    The dynamic ActionForm is implemented by the base class

    org.apache.struts.action.DynaActionForm, which extends theActionForm class.

  • 8/3/2019 Struts Module Version 1

    56/82

    Dyna Form

    The properties that the Action Form defines The validate() method The reset() method

    The properties for a DynaActionForm are configured in the Strutsconfiguration file,

    The reset() method is that you have a little less control over whatyou do during the method.

    The validation of the presentation data is a little more complicated,

  • 8/3/2019 Struts Module Version 1

    57/82

    Dyna Form-configuration file Form-property elements are defined for the dynamic form to have

    properties.

  • 8/3/2019 Struts Module Version 1

    58/82

    Accesing DynaForm in Action class

    DynaActionForm dynaActionForm = (DynaActionForm) form;

    String uname = String)dynaActionForm.get("username");

    String pwd =(String)dynaActionForm.get("password");

  • 8/3/2019 Struts Module Version 1

    59/82

    DispatchActionClass

    This class provides a mechanism for modularizing a set of related

    functions into a single action, and thus eliminates the need to createseparate, independent actions for each function.

    Action extends org.apache.struts.actions.Dispatch Action;

    Method call is determined based on the value of a requestparameter that is passed to it from the incoming request.

    At run time, DispatchAction manages routing requests to theappropriate method in its subclass.

  • 8/3/2019 Struts Module Version 1

    60/82

    DispatchAction

    Set up action mapping that specifies the name of a request parameter that

    will be used to select which method should be called for each request.

    execute method is omitted entirely, the custom methods have samesignature as execute

    Value should be the name of the method that applies

  • 8/3/2019 Struts Module Version 1

    61/82

    DispatchAction

    This class does not provide an implementation for the execute( ) method

    Struts configuration file for an an action mapping

  • 8/3/2019 Struts Module Version 1

    62/82

    LookupDispatch Action

    The org.apache.struts.actins.LookupDispatchAction , similar to Dispatch

    Action except that it uses java map

    The method name is selected based on the method specified in theproperties file

    This class can also have multiple methods, where one of the methods is

    invoked based on the value of a special request parameter that is specifiedthe configuration file.

    It uses the value of the request parameter to perform a reverse lookup fromthe resource bundle using the parameter value, and match it to a method inthe class.

    The getKeyMethodMap() method. returns a java.util.Map, which contains aset of key/value pairs.The keys of this Map should match those from theresource bundle.

    For ardAction

  • 8/3/2019 Struts Module Version 1

    63/82

    ForwardAction

    JSP should not be called directly and should be avoided.

    If there is a need, without having a need to go through an Action class.

    Use ForwardAction simply performs a forward to a URI that is configured forit.

    In the Struts configuration file, you specify an element using theForwardAction as the type attribute:

  • 8/3/2019 Struts Module Version 1

    64/82

    Steps in Using ForwardAction

  • 8/3/2019 Struts Module Version 1

    65/82

    The ActionForward Class

    Forwards are defined declaratively in the Struts configuration file.

    There are two types of forwards that can be defined,

    action-specific forward.

    These forwards are available only to their respective action.

    Action-specific forwards are defined by nesting the forward taginside an action tag,

    globalforward

    Global forwards are available throughout an application,

  • 8/3/2019 Struts Module Version 1

    66/82

    Forwards

    LOCAL Forward

    ...

    ...

    Local Forward

  • 8/3/2019 Struts Module Version 1

    67/82

    Local Forward

    ...

    ...

    ...

    ...

    ...

  • 8/3/2019 Struts Module Version 1

    68/82

    DAO Factory

    The DAO Factory Class :

    Its used to retrieve the object that implements the DAO Interface The DAO Interface

    The DAO AP I is defined with the methods

    The Concrete Class that implements the DAO interface

    Contains logic for accessing data from a specific data source.

    Data Transfer Objects Value Objects Used to transfer objects to transport data to and from the clients.

    A Business Logic Bean

    Contains the business logic of the application and will call DAO

    implementing concrete class for database related operations.

    In struts we use the Action class is used to call the DAO.

  • 8/3/2019 Struts Module Version 1

    69/82

    Data Access Object

    The database access code is removed from the action class.

    It has to be encapsulated behind the business API classes, using the DataAccess Object (DAO) pattern.

    To Access Using DAO Pattern

    1. Create a data access object factory.

    2. Create an interface that defines the methods that you need.3. Create a data access object that implements the interface and that contains

    the data access code.

    4. Refer to the data access object from the Struts action class.

  • 8/3/2019 Struts Module Version 1

    70/82

    DAO Factory

    package com.training;

    import java.sql.Connection;

    public class DAOFactory {

    public DAOFactory() {

    }

    public static UserDAO createUserDAO(Connection connection){

    return new OracleUserDAO(connection); }

    }

  • 8/3/2019 Struts Module Version 1

    71/82

    The Interface with Required Method

    package com.training;

    import java.util.ArrayList;

    public interface UserDAO {

    public ArrayList getCustomers(int pid);

    }

    Th D t A Obj t

  • 8/3/2019 Struts Module Version 1

    72/82

    The DataAccess Object public class OracleUserDAO implements UserDAO {

    private Connection connection;

    private DataSource dataSource; public OracleUserDAO(Connection connection) {

    this.connection = connection; }

    public ArrayList getCustomers(int pid){

    ArrayList customerList = new ArrayList();

    try{

    String sqlQuery = "SELECT * FROM sribooks where pub_id=?"; PreparedStatement prpStmt = connection.prepareStatement(sqlQuery);

    prpStmt.setInt(1,pid);

    ResultSet rs = prpStmt.executeQuery();

    while (rs.next()) {

    customerList.add(newBook(rs.getString(1),rs.getInt(2),rs.getFloat(3)));

    } rs.close();

    } catch (Exception e ) {

    e.printStackTrace();

    }

  • 8/3/2019 Struts Module Version 1

    73/82

    Action Class

    public class DataSourceConnectionAction extends Action {

    private DataSource dataSource; public ArrayList customerList = new ArrayList();

    public ActionForward execute(ActionMapping mapping, ActionForm form,

    HttpServletRequest request, HttpServletResponse response)

    throws Exception {

    HttpSession session = request.getSession(true)

    InitialContext ctx = new InitialContext();

    dataSource = (DataSource)ctx.lookup("myoracle");

    Connection conn = dataSource.getConnection();

    UserDAO dao = DAOFactory.createUserDAO(conn);

    customerList = dao.getCustomers(lac.getPubid());

    session.setAttribute("clist", customerList); }

    return (mapping.findForward("success")); }

  • 8/3/2019 Struts Module Version 1

    74/82

    Validation Framework

  • 8/3/2019 Struts Module Version 1

    75/82

    Why Struts Validation Framework?

    Issues with writing validate() method in ActionForm classes

    You have to write validate() method for each ActionForm class, whichresults in redundant code

    Changing validation logic requires recompiling

    Struts validation framework addresses these issues

    Validation logic is configured using built-in validation rules as opposedto writing it in Java code

  • 8/3/2019 Struts Module Version 1

    76/82

    Struts Validation Framework

    Originated from generic Validator framework from Jakarta

    Struts 1.1 includes this by default

    Allows declarative validation for many fields

    Formats

    Dates, Numbers, Email, Credit Card, Postal Codes

    Lengths

    Minimum, maximum

    Ranges

    The built-in validation rules come with Javascript that allows you to doclient side validation

    Custom Validation rules can be created and added to the definition file.

    Can also define regular expressions

    Things to do in order to use Validator

  • 8/3/2019 Struts Module Version 1

    77/82

    Things to do inorder to use Validator

    framework

    Configure Validator plugin

    Configure validation.xml file (and validation-rules.xml file)

    Extend ValidatorForm or DynaValidatorForm

    Set validate=true on Action Mappings

    Include the tag for client side validation in the form's JSP

    page

    How to Configure Validator Plugin

  • 8/3/2019 Struts Module Version 1

    78/82

    How to Configure Validator Plugin

    Validator plugin should be configured in struts-config.xml

    Just add the following element without any change

  • 8/3/2019 Struts Module Version 1

    79/82

    TwoValidatorConfiguration Files

    validation-rules.xml Contains global set of validation rules

    Provided by Struts framework

    validation.xml

    Application specific

    Provided by application developer

    It specifies which validation rules from validation-rules.xml file are usedby a particular ActionForm

    No need to write validate() code in ActionForm

    B ilt i i d lid ti l

  • 8/3/2019 Struts Module Version 1

    80/82

    Built-in required validation rule

    function validateRequired(form) {

    var isValid = true;

    ...

    Att ib t f < lid t > El t

  • 8/3/2019 Struts Module Version 1

    81/82

    Attributes of Element

    name: logical name of the validation rule

    classname, method: class and method that contains the validation logic

    methodParams: comma-delimited list of parameters for the method

    msg: key from the resource bundle

    Validator framework uses this to look up a message from Struts resourcebundle

    depends: other validation rules that should be called first

  • 8/3/2019 Struts Module Version 1

    82/82

    validation.xml

    Demo3.1