JaiswalTraining

Get the online training



Corejava Servlet Jsp  Php  Hibernate  Ajax Web Service   Ejb2.1 Ejb3.0 Struts Struts2  JPA Spring Ibatis   JSF    JSF2.0  CoreJavaDesignPattern    Jquery  Flex J2EE-Design-Patterns  Jboss7  Maven  Contact Me                                                                                                                                                                        
            IGNOU SMU PTU Project                                           Training                                                                                                                              
              

Contact Us  0091- 9210721663         jaiswaltraining@gmail.com





Corejava
Servlet
Jsp
Php
Hibernate
Ajax
Web Service
Ejb2.1
Ejb3.0
Struts  
Struts2
JPA
Spring
Ibatis
JSF
JSF2.0
CoreJavaDesignPattern
Jquery
Flex
J2EE-Design-Patterns
Jboss7
Maven








Struts Validation Framework

Overview
  • The validation framework provides a more versatile and maintainable solution to validation.
  • One of the stronger points of the validation framework is the Validator, a reusable component in which the logic of specific types of validations are implemented..
  • com.opensymphony.xwork2.Validateable and com.opensymphony.xwork2.Validation-
    Aware are the interfaces  that the ActionSupport classs implemented to use validation.
  • validate()  method is used for storing error messages generated
    when validation finds invalid data.
  • Action can extend the ActionSupport class, which provides a default implementation for both these
There are two possible ways to provide validation
  • Programmatically
  • Declaratively.
Programmatically

To provide validation programmatically, an action needs to implement the Validateable interface.
This has one method void validate()
This validate() method   contain the validations code.

  • To report validation problems back to the user, your action needs to implement the ValidationAware interface.
  • This is a more complex interface
    • It  provides method
      • to add validation errors
      •  determine whether there are currently validation errors, etc.
  • Programmatic validations should only be used when the validations are extremely complex.

HOw to Use
  • Each action that requires declarative validations will need a corresponding XML file.
  • For the action MyAction, the file would be named “MyAction-validation.xml
  • MyAction-validation.xml  should  be in the same package as the action.
  • The interceptor stack that processes the action will also need to include the
    “validation” (responsible for performing the validation) and
    “workflow” (responsible for redirecting the user back to the
    “input” result if a validation failure occurred) interceptors.

    Example of the validation file

    <!DOCTYPE validators PUBLIC
    "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
    "http://www.opensymphony.com/xwork/xwork-validator-
    1.0.2.dtd">
    <validators>
    <field name="count">
    <field-validator type="int" short circuit="true">
    <param name="min">1</param>
    <param name="max">100</param>
    <message key="invalid.count">
    Value must be between ${minand${max}
    </message>
    </field-validator>
    </field>
    <field name="name">
    <field-validator type="requiredstring">
    <message>You must enter a name.</message>
    </field-validator>
    </field>
    <validator type="expression"short-circuit="true">
    <param name="expression">
    email.equals(email2)
    </param>
    <message>Email not the same as email2</message>
    </validator>
    </validators>

Important points  to Remember in this example
  • Each field can have one or more “field-validator” nodes.
  • Each fields validators are executed in the order they are defined/.
  • Each field validator has a “short-circuit” attribute; if this is true and the validation fails, all further validations are skipped and a failed result returned for the field
  • The message node can include a “key” attribute which looks up the message to display to the user from a message bundle; the value of the node is then used if no message bundle key exists
  • Validator configuration information (such as min and max) as well as values from the value stack can be used in the validation message by placing the value between the tokens “${“ and “}”
  • Validators can have a scope of either “field” or “expression”; expression validators can work across multiple fields

Validator Types





Example:-
In this example name,  age  and salary field  is validated.
On validation it gives the proper message

  • First create one index.jsp
  • Add the code
index.jsp
<%page contentType="text/html; charset=UTF-8" %>
<%taglib prefix="s" uri="/struts-tags" %>
<html>
   <body>  
   <h1>Struts Validation Application</h1>
   Enter User Details:
     <s:form action="useraction" method="post">
           <s:textfield label="Name" name="name"/>
           <s:textfield label="Age" name="age"/>
           <s:textfield label="Salary" name="salary"/>
           <s:submit/>
     </s:form>
   </body>
 </html>


struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
  <constant name="struts.custom.i18n.resources" value="UserMessages" />
  <package name="default" extends="struts-default">
    <action name="useraction" class="myaction.UserAction">
      <result name="success">/user.jsp</result>
      <result name="input">/index.jsp</result>
    </action>
  </package>
</struts>  


Action file

  • Now we will create one Action file.
  • Save it as UserAction.java
  • Add the code as shown below
UserAction.java

package myaction;

import com.opensymphony.xwork2.ActionSupport;

public class UserAction extends ActionSupport {

  String name;
  int age;
  int salary;

  public String getName() {
    return name;
  }

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

  public int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.age = age;
  }

  public int getSalary() {
    return salary;
  }

  public void setSalary(int salary) {
    this.salary = salary;
  }

  public String execute() throws Exception {

    return SUCCESS;
  }
}


validation file

  • Now we will create one validation.xml file
  • For each action there should be  corresponding XML file.
  • So we will create UserAction-validation.xml file for our action
    UserAction

UserAction-validation.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE validators PUBLIC 
      "-//OpenSymphony Group//XWork Validator 1.0//EN" 
      "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>
  <field name="name">
    <field-validator type="requiredstring">
      <message key="error.name.blank" />
    </field-validator>
  </field>

  <field name="age">
    <field-validator type="int">
      <param name="min">18</param>
      <param name="max">45</param>
      <message>Enter between 18 and 45.</message>
    </field-validator>
  </field>

  <field name="salary">
    <field-validator type="int">
      <message key="error.salary.blank" />
    </field-validator>
  </field>
</validators>

  • Now create one user.jsp
  • This file contains the code to be displayed
    after proper validation.
user.jsp

<%page contentType="text/html; charset=UTF-8" %>
<%taglib prefix="s" uri="/struts-tags" %>
<html>
  
  <body>
  Thank you! <b><s:property value="name"/></b>. 
  <br><br>Your Age : <b><s:property value="age"/></b>
  <br><br>Your Salary : <b><s:property value="salary"/> $</b>
  </body>
</html>


web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 
  xmlns="http://java.sun.com/xml/ns/j2ee" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xsi:schemaLocation="http://java.sun.com/xml/ns/
j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <filter>
        <filter-name>struts2filter</filter-name>
        <filter-class>
          org.apache.struts2.dispatcher.FilterDispatcher
        </filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts2filter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

</web-app>


  • MessageResource file
UserMessages.properties


error.name.blank=User name cannot be left blank.
error.age.blank=age cannot be left blank.
error.salary.blank=salary cannot be left blank.

Download Source without lib

Download War with lib

Output::- 













Custom Validator

  • We declare our own custom validators in an application-local validators.xml file.
  • We put at the root of our classpath—directly under our src folder, which will be moved to
    WEB-INF/classes/ during the build.
  • FieldValidatorSupport  class is used in making custom validator.
  • public void validate(Object object) throws ValidationException
    this method of  
    FieldValidatorSupport is override when creating own custom validator.
Example:-

UsernameValidator.java

import com.opensymphony.xwork2.
validator.validators.FieldValidatorSupport;

import com.opensymphony.xwork2.validator.
ValidationException;


public class UsernameValidator extends
FieldValidatorSupport {
  private int minimumlength;
  private int maximumlength;

  public void setMinimumlength(int minimumlength) {
    this.minimumlength = minimumlength;
  }

  public void setMaximumlength(int maximumlength) {
    this.maximumlength = maximumlength;
  }

  public int getMinimumlength() {
    return minimumlength;
  }

  public int getMaximumlength() {
    return maximumlength;
  }

  public void validate(Object objectthrows ValidationException {
    String fieldname = getFieldName();
    String fieldvalue = (StringgetFieldValue(fieldname, object);

    if (fieldvalue == null || fieldvalue.length() == 0)
      addFieldError(fieldname, object);
    else if (fieldvalue.length() < getMinimumlength()
        || fieldvalue.length() > getMaximumlength())
      addFieldError(fieldname, object);
  }
}

validators.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group/
/XWork Validator Config 1.0//EN" "http://www.
opensymphony.com/xwork/xwork-validator-config-1.0.dtd"
>
<validators>
  <validator name="usernamevalidator" class="UsernameValidator"/>
</validators>


UserAction-validation.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE validators PUBLIC 
      "-//OpenSymphony Group//XWork Validator 1.0//EN" 
      "http://www.opensymphony.com/xwork/
xwork-validator-1.0.2.dtd"
>

<validators>

  <field name="name">
    <field-validator type="usernamevalidator">
      <param name="minimumlength">6</param>
      <param name="maximumlength">8</param>
      <message>Username cannot be left blank
 OR User name must be six to

        eight characters long.</message>
    </field-validator>
  </field>

  <field name="age">
    <field-validator type="int">
      <param name="min">18</param>
      <param name="max">45</param>
      <message>Enter between 18 and 45.</message>
    </field-validator>
  </field>

  <field name="salary">
    <field-validator type="int">
      <message key="error.salary.blank" />
    </field-validator>
  </field>


</validators>

Download Zip code

Output:-









Validation Using validate() method of ActionSupport Class.

Example:- without using UserAction-validation xml file.

package myaction;

import com.opensymphony.xwork2.ActionSupport;

public class UserAction extends ActionSupport {

  String name;
  int age;
  int salary;

  public String getName() {
    return name;
  }

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

  public int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.age = age;
  }

  public int getSalary() {
    return salary;
  }

  public void setSalary(int salary) {
    this.salary = salary;
  }

  public void validate() {
    if (getName() == null || getName().length() == 0)
      addFieldError("name""Username cannot be left blank.");
    if (getAge() == 0)
      addFieldError("age""Age cannot be left Zero.");
    if (getSalary() == 0)
      addFieldError("salary""Salary cannot be left Zero.");

  }

  public String execute() throws Exception {

    return SUCCESS;
  }
}



output:-



download  Code