Showing posts with label Struts 2. Show all posts
Showing posts with label Struts 2. Show all posts

Struts File Upload and Save

We are receiving lots of comments regarding "Struts file upload example". It does not contain any code illustrating how to save the file on the server . Now, the current example will provide you with the code to upload the file ,in the upload directory of server.

In this tutorial you will learn how to use Struts program to upload on the Server and display a link to the user to download the uploaded file . The interface org.apache.struts.upload.FormFile has a prime role in uploading a file in a Struts application. This interface represents a file that has been uploaded by a client. It is the only interface or class in Upload package which is referenced directly by a Struts application.

Creating Form Bean

Our form bean class contains only one property theFile, which is of type org.apache.struts.upload.FormFile.

Here is the code of FormBean (StrutsUploadAndSaveForm.java):
package roseindia.net;


import org.apache.struts.action.*;
import org.apache.struts.upload.FormFile;



/**
* @author Amit Gupta
* @Web http://www.roseindia.net
* @Email struts@roseindia.net
*/

/**
* Form bean for Struts File Upload.
*
*/
public class StrutsUploadAndSaveForm extends ActionForm
{
private FormFile theFile;

/**
* @return Returns the theFile.
*/
public FormFile getTheFile() {
return theFile;
}
/**
* @param theFile The FormFile to set.
*/
public void setTheFile(FormFile theFile) {
this.theFile = theFile;
}
}

Creating Action Class

In our previous article entitled "Struts File Upload Example", we just had action class simply calling the getTheFile() function on the FormBean object to retrieve the reference of the uploaded file. Then the reference of the FormFile was used to get the uploaded file and its information. Now further we retrieve the Servers upload directory's real path using ServletContext's getRealPath() and saving the file.

Code of StrutsUploadAndSaveAction.java:

package roseindia.net;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import java.io.*;

/**
* @author Amit Gupta
* @Web http://www.roseindia.net
* @Email struts@roseindia.net
*/

/**
* Struts File Upload Action Form.
*
*/
public class StrutsUploadAndSaveAction extends Action
{
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception{
StrutsUploadAndSaveForm myForm = (StrutsUploadAndSaveForm)form;

// Process the FormFile
FormFile myFile = myForm.getTheFile();
String contentType = myFile.getContentType();
//Get the file name
String fileName = myFile.getFileName();
//int fileSize = myFile.getFileSize();
byte[] fileData = myFile.getFileData();
//Get the servers upload directory real path name
String filePath = getServlet().getServletContext().getRealPath("/") +"upload";
/* Save file on the server */
if(!fileName.equals("")){
System.out.println("Server path:" +filePath);
//Create file
File fileToCreate = new File(filePath, fileName);
//If file does not exists create file
if(!fileToCreate.exists()){
FileOutputStream fileOutStream = new FileOutputStream(fileToCreate);
fileOutStream.write(myFile.getFileData());
fileOutStream.flush();
fileOutStream.close();
}


}
//Set file name to the request object
request.setAttribute("fileName",fileName);

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

Defining form Bean in struts-config.xml file

Add the following entry in the struts-config.xml file for defining the form bean:

name="FileUploadAndSave"
type="roseindia.net.StrutsUploadAndSaveForm"/>

Defining Action Mapping

Add the following action mapping entry in the struts-config.xml file:

path="/FileUploadAndSave"
type="roseindia.net.StrutsUploadAndSaveAction"
name="FileUploadAndSave"
scope="request"
validate="true"
input="/pages/FileUploadAndSave.jsp">


Developing jsp pages

Code of the jsp (FileUploadAndSave.jsp) file to upload is as follows

<%@ taglib uri="/tags/struts-bean" prefix="bean" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>



Struts File Upload and Save Example






















File Upload on Server



File Name



Upload File






code for the success page (downloaduploadedfile.jsp) is:




Success



<%
String fileName=(String)request.getAttribute("fileName");
%>

File Successfully Received


">Click here to download





Add the following line in the index.jsp to call the form.


  • Struts File Upload


    Example shows you how to Upload File with Struts.

  • Building Example and Testing

    To build and deploy the application go to Struts\strutstutorial directory and type ant on the command prompt. This will deploy the application. Open the browser and navigate to the Struts File Upload page. Your browser should display the file upload form:

    Now , Browse the file needed to upload and click Upload File Button. Browser will display that file has successfully received on the server.

    read more “Struts File Upload and Save”

    Struts File Upload Example

    In this tutorial you will learn how to use Struts to write program to upload files. The interface org.apache.struts.upload.FormFile is the heart of the struts file upload application. This interface represents a file that has been uploaded by a client. It is the only interface or class in upload package which is typically referenced directly by a Struts application.

    Creating Form Bean

    Our form bean class contains only one property theFile, which is of type org.apache.struts.upload.FormFile.

    Here is the code of FormBean (StrutsUploadForm.java):
    package roseindia.net;


    import org.apache.struts.action.*;
    import org.apache.struts.upload.FormFile;



    /**
    * @author Deepak Kumar
    * @Web http://www.roseindia.net
    * @Email roseindia_net@yahoo.com
    */

    /**
    * Form bean for Struts File Upload.
    *
    */
    public class StrutsUploadForm extends ActionForm
    {
    private FormFile theFile;

    /**
    * @return Returns the theFile.
    */
    public FormFile getTheFile() {
    return theFile;
    }
    /**
    * @param theFile The FormFile to set.
    */
    public void setTheFile(FormFile theFile) {
    this.theFile = theFile;
    }
    }

    Creating Action Class

    Our action class simply calls the getTheFile() function on the FormBean object to retrieve the reference of the uploaded file. Then the reference of the FormFile is used to get the uploaded file and its information. Here is the code of our action class(StrutsUploadAction.java):

    package roseindia.net;

    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    import org.apache.struts.action.Action;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;
    import org.apache.struts.upload.FormFile;
    /**
    * @author Deepak Kumar
    * @Web http://www.roseindia.net
    * @Email roseindia_net@yahoo.com
    */

    /**
    * Struts File Upload Action Form.
    *
    */
    public class StrutsUploadAction extends Action
    {
    public ActionForward execute(
    ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response) throws Exception{
    StrutsUploadForm myForm = (StrutsUploadForm)form;

    // Process the FormFile
    FormFile myFile = myForm.getTheFile();
    String contentType = myFile.getContentType();
    String fileName = myFile.getFileName();
    int fileSize = myFile.getFileSize();
    byte[] fileData = myFile.getFileData();
    System.out.println("contentType: " + contentType);
    System.out.println("File Name: " + fileName);
    System.out.println("File Size: " + fileSize);

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

    Defining form Bean in struts-config.xml file

    Add the following entry in the struts-config.xml file for defining the form bean:

    name="FileUpload"
    type="roseindia.net.StrutsUploadForm"/>

    Defining Action Mapping

    Add the following action mapping entry in the struts-config.xml file:

    path="/FileUpload"
    type="roseindia.net.StrutsUploadAction"
    name="FileUpload"
    scope="request"
    validate="true"
    input="/pages/FileUpload.jsp">


    Developing jsp page

    Code of the jsp (FileUpload.jsp) file to upload is as follows:

    <%@ taglib uri="/tags/struts-bean" prefix="bean" %>
    <%@ taglib uri="/tags/struts-html" prefix="html" %>



    Struts File Upload Example























    Please Enter the Following Details



    File Name



    Upload File






    Note that we are setting the encrypt property of the form to enctype="multipart/form-data".

    code for the success page (uploadsuccess.jsp) is:




    Success




    File Successfully Received





    Add the following line in the index.jsp to call the form.


  • Struts File Upload


    Example shows you how to Upload File with Struts.

  • Building Example and Testing

    To build and deploy the application go to Struts\strutstutorial directory and type ant on the command prompt. This will deploy the application. Open the browser and navigate to the FileUpload.jsp page. Your browser should display the file upload form:

    read more “Struts File Upload Example”

    Struts DynaActionForm

    In this tutorial you will learn how to create Struts DynaActionForm. We will recreate our address form with Struts DynaActionForm. DynaActionForm is specialized subclass of ActionForm that allows the creation of form beans with dynamic sets of properties, without requiring the developer to create a Java class for each type of form bean. DynaActionForm eliminates the need of FormBean class and now the form bean definition can be written into the struts-config.xml file. So, it makes the FormBean declarative and this helps the programmer to reduce the development time.

    In this tutorial we will recreate the add form with the help of DynaActionForm. It also shows you how you can validate use input in the action class.

    Adding DynaActionForm Entry in struts-config.xml

    First we will add the necessary entry in the struts-config.xml file. Add the following entry in the struts-config.xml file. The form bean is of org.apache.struts.action.DynaActionForm type. The tag is used to define the property for the form bean.

    We have defined three properties for our dynamic form bean.
    type="org.apache.struts.action.DynaActionForm">



    Adding action mapping

    Add the following action mapping in the struts-config.xml file:

    name="DynaAddressForm"
    scope="request"
    validate="true"
    input="/pages/DynaAddress.jsp">




    Creating Action Class

    Code for action class is as follows:

    package roseindia.net;

    /**
    * @author Deepak Kumar
    * @Web http://www.roseindia.net
    * @Email roseindia_net@yahoo.com
    */

    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    import org.apache.struts.action.Action;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;
    import org.apache.struts.action.DynaActionForm;
    import org.apache.struts.action.ActionMessages;
    import org.apache.struts.action.ActionMessage;


    public class AddressDynaAction extends Action
    {
    public ActionForward execute(
    ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response) throws Exception{

    DynaActionForm addressForm = (DynaActionForm)form;

    //Create object of ActionMesssages
    ActionMessages errors = new ActionMessages();
    //Check and collect errors
    if(((String)addressForm.get("name")).equals("")) {
    errors.add("name",new ActionMessage("error.name.required"));
    }

    if(((String)addressForm.get("address")).equals("")) {
    errors.add("address",new ActionMessage("error.address.required"));
    }

    if(((String)addressForm.get("email")).equals("")) {
    errors.add("email",new ActionMessage("error.emailaddress.required"));
    }
    //Saves the error
    saveErrors(request,errors);
    //Forward the page
    if(errors.isEmpty()){
    return mapping.findForward("success");
    }else{
    return mapping.findForward("invalid");
    }
    }
    }

    Creating the JSP file

    We will use the Dyna Form DynaAddressForm created above in the jsp file. Here is the code of the jsp(DynaAddress.jsp) file.

    <%@ taglib uri="/tags/struts-bean" prefix="bean" %>
    <%@ taglib uri="/tags/struts-html" prefix="html" %>



    <bean:message key="welcome.title">
































    Please Enter the Following Details



    Name



    Address



    E-mail address



    Save

    Cancel






    Add the following line in the index.jsp to call the form.


  • Dyna Action Form Example


    Example shows you how to use DynaActionForm.

  • Building Example and Testing

    To build and deploy the application go to Struts\strutstutorial directory and type ant on the command prompt. This will deploy the application. Open the browser and navigate to the DynaAddress.jsp page. Without entering anything in the form and submitting the submit button, your browser should show the following out put.

    read more “Struts DynaActionForm”

    Using tiles-defs.xml in Tiles Application

    In the last section we studied how to forward the request (call) to a jsp page which specifies which tiles layout definition should be used to apply to the content. In this section I will show you how to use the a definition in the tiles-defs.xml for generating the content.

    In Tiles we can define the definition in the tiles-defs.xml which specifies the different components to "plugin" to generate the output. This eliminates the need to define extra jsp file for each content file. For example in the last section we defined example.jsp to display the content of content.jsp file. In this section I will show you how to eliminate the need of extra jsp file using tiles-defs.xml file.

    Steps to Use the tiles-defs.xml

    Setup the Tiles plugin in struts-config.xml file.
    Add the following code in the struts-config.xml (If not present). This enables the TilesPlugin to use the /WEB-INF/tiles-defs.xml file.





    Defining the tiles-defs.xml
    In this file we are defining the different components to "plugin". Here is the code:







    The name of the definition is Tiles.Example, we will use this in struts-config.xml (While creating forwards in struts-config.xml file) file. The page attribute defines the template file to be used and the put tag specifies the different components to "plugin". Your tiles-defs.xml should look like:



    "-//Apache Software Foundation//DTD Tiles Configuration 1.1//EN"
    "http://jakarta.apache.org/struts/dtds/tiles-config_1_1.dtd">
















    Configure the Struts Action to use Tiles Definition
    Open the struts-config.xml file and add the following code:

    forward="Tiles.Example"/>

    With Tiles, the action points to the Tiles definition, as shown in the above code. In this code we are using the Tiles.Example definition which we have defined in the tiles-defs.xml file. Without Tiles, forward and action definitions point directly to JSPs. With Tiles, they point to the page's definition in the Tiles configuration file.

    Testing the Application
    Create a link in index.jsp to call the Example. Code added are:


  • Using tiles-defs.xml


    Example shows you how to use tiles-defs.xml file.
  • To test the application build it using ant and deploy on the JBoss server. Type http://localhost:8080/strutstutorial/index.jsp in the bowser and select the Using tiles-defs.xml link. Your browser should show the page.

    read more “Using tiles-defs.xml in Tiles Application”

    Developing Simple Struts Tiles Application

    Introduction
    In this section I will show you how to develop simple Struts Tiles Application. You will learn how to setup the Struts Tiles and create example page with it.

    What is Struts Tiles?
    Tiles is a framework for the development user interface. Tiles is enables the developers to develop the web applications by assembling the reusable tiles (jsp, html, etc..). Tiles uses the concept of reuse and enables the developers to define a template for the web site and then use this layout to populate the content of the web site. For example, if you have to develop a web site having more that 500 page of static content and many dynamically generated pages. The layout of the web site often changes according to the business requirement. In this case you can use the Tiles framework to design the template for the web site and use this template to populate the contents. In future if there is any requirement of site layout change then you have to change the layout in one page. This will change the layout of you whole web site.

    Steps To Create Tiles Application
    Tiles is very useful framework for the development of web applications. Here are the steps necessary for adding Tiles to your Struts application:

    1. Add the Tiles Tag Library Descriptor (TLD) file to the web.xml.
    2. Create layout JSPs.
    3. Develop the web pages using layouts.
    4. Repackage, run and test application.

    Add the Tiles TLD to web.xml file
    Tiles can can be used with or without Struts. Following entry is required in the web.xml file before you can use the tiles tags in your application.


    /tags/struts-tiles
    /WEB-INF/struts-tiles.tld


    Create layout JSPs.

    Our web application layout is divided into four parts: To Banner, Left Navigation Bar, Content Area and Bottom of the page for copy right information. Here is the code for out template (template.jsp):

    <%@ page language="java" %>
    <%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles" %>



    <b><span style="color:#800000;"><tiles:getasstring name="title" ignore="true"></span></b>



















    We have defined the structure for web application using the appropriate html and did the following things:

    • Referenced the /WEB-INF/struts-tiles.tld TLD.
    • Used the string parameters to display title using the tiles:getAsString tag. If the attribute ignore="true" then Tiles ignore the missing parameter. If this is true then the Tiles framework will through the exception in case the parameter is missing.
    • To insert the content JSP, the tiles:insert tag is used, which inserts any page or web resources that framework refers to as a title. For Example inserts the header web page.

    Develop the web pages using layouts
    Now we will use tile layout create a page to display the content page in the in our application. For every content page there is additional jsp file for inserting the content in the Layout, so we have to create two jsp files one for content and another for displaying the content. In our example these file are example.jsp and content.jsp. Here is the code for both the files:

    content.jsp

    Welcome to the Title Tutorial


    This is the content page

    The content.jsp simply define the content of the page. The content may be dynamic or static depending on the requirements.

    example.jsp

    <%@ page language="java" %>
    <%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles" %>







    The code specifies the tiles layout page to be used. We have set the flush attribute to true, this makes the tile file to be written to browser before the rest of the page. To specify the title of the page is used. The following code is used to insert the actual pages in the template.:




    The top.jsp will be inserted in the layout's header region. The left.jsp will be inserted in the layout's menu region. The content.jsp wil be inserted in the layout's body region and the bottom.jsp will be inserted in the bottom region.

    Repackage, run and test application
    Add the following code in the index.jsp to test the this tile example:


  • Tiles Example


    Example of creating first tile application.
  • Use the ant tool to build the application and deploy on the server. To test the application go to the index.jps and click on the Tiles Example link.

    read more “Developing Simple Struts Tiles Application”

    Creating Custom Validators in STRUTS

    Author: Murthy Gandikota (murthy64@hotmail.com)

    In this tutorial you will learn how to develop Custom Validators in your Struts 1.3 applications. Struts Validator framework provides many validation rules that can be used in the web applications. If you application needs special kind of validation, then you can extend the validator framework to develop your own validation rule.

    The client-side validation in Struts is well known. Here are some of the available features:

    • required
    • requiredif
    • validwhen
    • minlength
    • maxlength
    • mask
    • byte
    • short
    • integer
    • long
    • float
    • double
    • byteLocale
    • shortLocale
    • integerLocale
    • longLocale
    • floatLocale
    • doubleLocale
    • date
    • intRange
    • longRange
    • floatRange
    • doubleRange
    • creditCard
    • email
    • url

    These are found in the validator-rules.xml inside the tags. The validator-rules.xml file is found in the commons-validator jar.

    Let us know create a new validator for entering the name field of a form. The form should accept only "administrator" for the name field. To accomplish this edit the validator-rules.xml and add the following code under the tag:

    classname="org.apache.struts.validator.FieldChecks"
    method="validateName"
    methodParams="java.lang.Object,
    org.apache.commons.validator.ValidatorAction,
    org.apache.commons.validator.Field,
    org.apache.struts.action.ActionMessages,
    org.apache.commons.validator.Validator,
    javax.servlet.http.HttpServletRequest"
    msg="errors.name">
    function validateName(form) {
    var isValid = true;
    var focusField = null;
    var i = 0;
    var fields = new Array();

    var omatchName= eval('new ' + jcv_retrieveFormName(form) + '_matchname() ');

    for (var x in omatchName) {
    if (!jcv_verifyArrayElement(x, omatchName[x])) {
    continue;
    }
    var field = form[omatchName[x][0]];

    if (!jcv_isFieldPresent(field)) {
    fields[i++] = omatchName[x][1];
    isValid=false;
    } else if (field.value != "administrator") {
    fields[i++]=omatchName[x][1];
    isValid=false;
    }
    }

    if (fields.length > 0) {
    jcv_handleErrors(fields, focusField);
    }
    return isValid;
    }
    ]]>


    To understand the above code:

    • matchname is the new validator we are creating; use can use anything you want (e.g. matchAdmin) remembering that this will be used in another file which will be described later
    • the error message issued in the browser has the key errors.name; you can have any name here like errors.admin; once again this will be explained later
    • the Java Script function to call is declared in the method attribute of the validator tag; in the above it is called validateName; you can have any valid Java Script function name (e.g. validateAdmin)
    • the Java Script to process this tag is declared inside CDATA; note that the function name should match EXACTLY with the name declared in the method attribute of the validator tag
    • the field.value != "administrator" is where we actually test the value entered in the browser; you can substitute any string in the place of "administrator"; also you can do more sophisticated checking (e.g. replace all blanks; check for upper/lower case, etc.) if you are an experienced Java Script programmer

    To use our matchname validator create a file validation.xml and add the following lines:





    depends="matchname">




    Copy the files validation.xml and validator-rules.xml to the directory where your struts-config.xml resides. Let us say it is WEB-INF. Next we have to create the error message for errors.name. Create a directory WEB-INF/resources and a file in this directory with the name application.properties. Add the following lines to application.properties

    AdminForm.name=Name
    errors.name={0} should be administrator.
    errors.required={0} is required.
    errors.minlength={0} can not be less than {1} characters.
    errors.maxlength={0} can not be greater than {1} characters.
    errors.invalid={0} is invalid.
    errors.byte={0} must be a byte.
    errors.short={0} must be a short.
    errors.integer={0} must be an integer.
    errors.long={0} must be a long.
    errors.float={0} must be a float.
    errors.double={0} must be a double.
    errors.date={0} is not a date.
    errors.range={0} is not in the range {1} through {2}.
    errors.creditcard={0} is an invalid credit card number.
    errors.email={0} is an invalid e-mail address.

    Edit struts-configuration.xml and add the following lines



    path="/AdminFormValidation"
    type="test.AdminForm"
    name="AdminForm"
    scope="request"
    validate="true"
    input="admin.jsp">







    property="pathnames"
    value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>

    Create a JSP file as follows:


    <%@ taglib uri="struts-bean.tld" prefix="bean" %>
    <%@ taglib uri="struts-html.tld" prefix="html" %>



    Administrator Test







    This application shows the use of Struts Validator.

    The following form contains fields that are processed by Struts Validator.

    Fill in the form and see how JavaScript generated by Validator Framework validates the form.

















    Name



    Save

    Cancel










    Then we create the success.jsp


    <% out.println("SUCCESS") %>

    Then we create the Java Class for the AdminForm

    package test;

    import javax.servlet.http.HttpServletRequest;

    import org.apache.struts.action.*;


    /**
    * Form bean for the Admin Entry Screen.
    *
    */
    public class AdminForm extends ActionForm
    {
    private String name=null;

    public void setName(String name){
    this.name=name;
    }

    public String getName(){
    return this.name;
    }


    /**
    * Reset all properties to their default values.
    *
    * @param mapping The mapping used to select this instance
    * @param request The servlet request we are processing
    */
    public void reset(ActionMapping mapping, HttpServletRequest request) {
    this.name=null;
    }

    /**
    * Reset all properties to their default values.
    *
    * @param mapping The mapping used to select this instance
    * @param request The servlet request we are processing
    * @return errors
    */
    public ActionErrors validate(
    ActionMapping mapping, HttpServletRequest request ) {
    ActionErrors errors = new ActionErrors();

    if( getName() == null || getName().length() < 1 ) {
    errors.add("name",new ActionMessage("error.name.required"));
    }
    }

    return errors;
    }

    }

    Create the AdminAction.java


    package test;

    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    import org.apache.struts.action.Action;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;

    public class AdminAction extends Action
    {
    public ActionForward execute(
    ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response) throws Exception{
    return mapping.findForward("success");
    }
    }

    Finally compile the classes and restart the web server and view the AdminForm.jsp

    read more “Creating Custom Validators in STRUTS”

    Client Side Address Validation in Struts

    In this lesson we will create JSP page for entering the address and use the functionality provided by Validator Framework to validate the user data on the browser. Validator Framework emits the JavaScript code which validates the user input on the browser. To accomplish this we have to follow the following steps:

    1. Enabling the Validator plug-in: This makes the Validator available to the system.
    2. Create Message Resources for the displaying the error message to the user.
    3. Developing the Validation rules We have to define the validation rules in the validation.xml for the address form. Struts Validator Framework uses this rule for generating the JavaScript for validation.
    4. Applying the rules: We are required to add the appropriate tag to the JSP for generation of JavaScript.
    5. Build and test: We are required to build the application once the above steps are done before testing.

    Enabling the Validator plug- in
    To enable the validator plug-in open the file struts-config.xml and make sure that following line is present in the file.



    property="pathnames"
    value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>

    Creating Message Resources
    Message resources are used by the Validator Framework to generate the validation error messages. In our application we need to define the messages for name, Address and E-mail address. Open the Struts\strutstutorial\web\WEB-INF\MessageResources.properties file and add the following lines:
    AddressForm.name=Name
    AddressForm.address=Address
    AddressForm.emailAddress=E-mail address

    Developing Validation rules
    In this application we are adding only one validation that the fields on the form should not be blank. Add the following code in the validation.xml.



    depends="required">


    depends="required">


    depends="required">


    The above definition defines the validation for the form fields name, address and emailAddress. The attribute depends="required" instructs the Validator Framework to generate the JavaScript that checks that the fields are not left blank. If the fields are left blank then JavaScript shows the error message. In the error message the message are taken from the key defined in the key=".."/> tag. The value of key is taken from the message resources (Struts\strutstutorial\web\WEB-INF\MessageResources.properties).

    Applying Validation rules to JSP
    Now create the AddressJavascriptValidation.jsp file to test the application. The code for AddressJavascriptValidation.jsp is as follows:

    <%@ taglib uri="/tags/struts-bean" prefix="bean" %>
    <%@ taglib uri="/tags/struts-html" prefix="html" %>



    <bean:message key="welcome.title">







    This application shows the use of Struts Validator.

    The following form contains fields that are processed by Struts Validator.

    Fill in the form and see how JavaScript generated by Validator Framework validates the form.





























    Please Enter the Following Details

    Name



    Address



    E-mail address



    Save

    Cancel










    The code is used to plug-in the Validator JavaScript.

    Create the following entry in the struts-config.xml for the mapping the /AddressJavascriptValidation url for handling the form submission through AddressJavascriptValidation.jsp.

    path="/AddressJavascriptValidation"
    type="roseindia.net.AddressAction"
    name="AddressForm"
    scope="request"
    validate="true"
    input="/pages/AddressJavascriptValidation.jsp">

    Add the following line in the index.jsp to call the form.


  • /pages/AddressJavascriptValidation.jsp">Client Side Validation for Address Form


    The Address Form that validates the data on the client side using Stuts Validator generated JavaScript.
  • Building Example and Testing

    To build and deploy the application go to Struts\strutstutorial directory and type ant on the command prompt. This will deploy the application. Open the browser and navigate to the AddressJavascriptValidation.jsp page. Your browser should show the following out put.

    If the fields are left blank and Save button is clicked, browser shows the error message.

    In this lesson you learned how to use Struts Validator Framework to validate the form on client browser.

    read more “Client Side Address Validation in Struts”

    Struts Validator Framework

    This lesson introduces you the Struts Validator Framework. In this lesson you will learn how to use Struts Validator Framework to validate the user inputs on the client browser.

    Introduction to Validator Framework

    Struts Framework provides the functionality to validate the form data. It can be use to validate the data on the users browser as well as on the server side. Struts Framework emits the java scripts and it can be used to validate the form data on the client browser. Server side validation of the form can be accomplished by sub classing your From Bean with DynaValidatorForm class.

    The Validator framework was developed by David Winterfeldt as third-party add-on to Struts. Now the Validator framework is a part of Jakarta Commons project and it can be used with or without Struts. The Validator framework comes integrated with the Struts Framework and can be used without doing any extra settings.

    Using Validator Framework

    Validator uses the XML file to pickup the validation rules to be applied to an form. In XML validation requirements are defined applied to a form. In case we need special validation rules not provided by the validator framework, we can plug in our own custom validations into Validator.

    The Validator Framework uses two XML configuration files validator-rules.xml and validation.xml. The validator-rules.xml defines the standard validation routines, these are reusable and used in validation.xml. to define the form specific validations. The validation.xml defines the validations applied to a form bean.

    Structure of validator-rule.xml

    The validation-rules.xml is provided with the Validator Framework and it declares and assigns the logical names to the validation routines. It also contains the client-side javascript code for each validation routine. The validation routines are java methods plugged into the system to perform specific validations.

    Following table contains the details of the elements in this file:

    Element

    Attributes and Description

    form-validation

    This is the root node. It contains nested elements for all of the other configuration settings.

    global

    The validator details specified within this, are global and are accessed by all forms.

    validator

    The validator element defines what validators objects can be used with the fields referenced by the formset elements.

    The attributes are:

    • name: Contains a logical name for the validation routine

    • classname: Name of the Form Bean class that extends the subclass of ActionForm class

    • method: Name of the method of the Form Bean class

    • methodParams: parameters passed to the method

    • msg:Validator uses Struts' Resource Bundle mechanism for externalizing error messages. Instead of having hard-coded error messages in the framework, Validator allows you to specify a key to a message in the ApplicationResources.properties file that should be returned if a validation fails. Each validation routine in the validator-rules.xml file specifies an error message key as value for this attribute.

    • depends: If validation is required, the value here is specified as 'required' for this attribute.

    • jsFunctionName: Name of the javascript function is specified here.

    javascript

    Contains the code of the javascript function used for client-side validation. Starting in Struts 1.2.0 the default javascript definitions have been consolidated to commons-validator. The default can be overridden by supplying a element with a CDATA section, just as in struts 1.1.

    The Validator plug-in (validator-rules.xml) is supplied with a predefined set of commonly used validation rules such as Required, Minimum Length, Maximum length, Date Validation, Email Address validation and more. This basic set of rules can also be extended with custom validators if required.

    Structure of validation.xml

    This validation.xml configuration file defines which validation routines that is used to validate Form Beans. You can define validation logic for any number of Form Beans in this configuration file. Inside that definition, you specify the validations you want to apply to the Form Bean's fields. The definitions in this file use the logical names of Form Beans from the struts-config.xml file along with the logical names of validation routines from the validator-rules.xml file to tie the two together.

    Element

    Attributes and Description

    form-validation

    This is the root node. It contains nested elements for all of the other configuration settings

    global

    The constant details are specified in element within this element.

    constant

    Constant properties are specified within this element for pattern matching.

    constant-name

    Name of the constant property is specified here

    constant-value

    Value of the constant property is specified here.

    formset

    This element contains multiple

    elements

    form

    This element contains the form details.
    The attributes are:

    name
    :Contains the form name. Validator uses this logical name to map the validations to a Form Bean defined in the struts-config.xml file

    field

    This element is inside the form element, and it defines the validations to apply to specified Form Bean fields.

    The attributes are:

    • property: Contains the name of a field in the specified Form Bean

    • depends: Specifies the logical names of validation routines from the validator-rules.xml file that should be applied to the field.

    arg

    A key for the error message to be thrown incase the validation fails, is specified here

    var

    Contains the variable names and their values as nested elements within this element.

    var-name

    The name of the criteria against which a field is validated is specified here as a variable

    var-value

    The value of the field is specified here

    Example of form in the validation.xml file:



    depends="required">


    depends="required,mask">


    mask
    ^[0-9a-zA-Z]*$


    The tag to allow front-end validation based on the xml in validation.xml. For example the code: generates the client side java script for the form "logonForm" as defined in the validation.xml file. The when added in the jsp file generates the client site validation script.

    In the next lesson we will create a new form for entering the address and enable the client side java script with the Validator Framework.

    read more “Struts Validator Framework”