Labels

.NET Job Questions About Java Absract class Abstract class Abstract Class and Interface Aggregation ajax aop apache ofbiz Apache ofbiz tutrial Association authentication autocad basics batch Binary Tree bootstrap loader in java build Builder design pattern C++ Job Questions caching CallableStatement in java certifications Chain of responsibility Design pattern charts check parentheses in a string Classes classloader in java classloading concept code quality collage level java program Composition concurrency Concurrency Tutorial Converting InputStream to String Core Java core java concept core java interview questions Core Java Interview Questions Core Java Questions core java tutorial CyclicBarrier in Java data structures database Database Job Questions datetime in c# DB Db2 SQL Replication deserialization in java Design Patterns designpatterns Downloads dtd Eclipse ejb example/sample code exception handling in core java file handling injava File I/O vs Memory-Mapped Filter first program in spring flex Garbage Collection Generics concept in java grails groovy and grails Guice Heap hibernate Hibernate Interview Questions how-to IBM DB2 IBM DB2 Tutorial ide immutable Interceptor Interface interview Interview Questions for Advanced JAVA investment bank j2ee java JAVA Code Examples Java 7 java changes java class loading JAVA Classes and Objects Java Classloader concept Java classloading concept java cloning concept java collection Java collection interview questions Java Collections java concurrency Java CountDownLatch java definiton Java design pattern Java EE 5 Java EE 6 Java Exceptions Java file Java Garbage Collection Java generics Java Glossary java hot concept java immutable concept Java Interface Java interview Question java interview question 2012 java interview question answer Java Interview Questions Java Interview Questions and Answers java interview topic java investment bank Java Job Questions java multithreading java multithreading concept java new features Java Packages java proxy object java questions Java Serialization Java serialization concept java serialization interview question java session concept java string Java Swings Questions java synchronization java threading Java Threads Questions java tutorial java util; java collections; java questions java volatile java volatile interview question Java Wrapper Classes java.java1.5 java.lang.ClassCastException JavaNotes javascript JAX-WS jdbc JDBC JDBC Database connection jdk 1.5 features JDK 1.5 new features Concurrent HashMap JMS interview question JMS tutorial job JSESSIONID concept JSESSIONID interview Question JSF jsp JSP Interview Question JSP taglib JSTL with JSP Junit Junit Concept Junit interview question.Best Practices to write JUnit test cases in Java JVM Linux - Unix tutorial Marker Interfaces MD5 encryption and decryption messaging MNC software java interview question musix NCR java interview question Networking Job Questions news Object Serialization Objects ojdbc14.jar OOP Oracle Oracle SQL Query for two timestamp difference orm own JavaScript function call in Apache ofbiz Packages Palm Apps patterns pdf persistence Portal Portlet Spring Integration Prime number test in java programs Rails Reboot remote computers REST Ruby Sample application schema SCJP security Senior java developer interviews servlet3 servlets session tracking singleton design pattern Spring Spring 2.5 Framework spring ebook Spring framework concept spring MVC spring pdf Spring Security Spring Security interview questions SQL SQL performance SQL Query to create xml file Sql Query tuning ssis and ssrs StAX and XML string concept string immutable string in java strings struts Struts2 Struts2 integration synchronization works in java Technical Interview testing tips Tomcat top Tutorial Volatile in deep Volatile working concept web Web Developer Job Questions web services weblogic Weblogic Application Server websphere what is JSESSIONID xml XML parsing in java XML with Java xslt


Thursday, 11 July 2013

Struts 2 Validation : Annotations

In a previous post, I described how to use validations in Struts 2, using XML validation rules. This post will show how to use Annotation based validation in Struts 2. For this example I used the add transaction part of google's portfolio manager (noticed that they do not have validations over there). Struts 2 provides a number of validators for XML based validation rules. All of them have respective annotations defined and can be used in place of XML validation rules. In the example, we will use the @RequiredStringValidator, @RegexFieldValidator and also see how to parameterize messages when using annotations.

Follow these steps to implement the example ... There's more

  1. Create a dynamic web project in Eclipse.
  2. Copy the following jar files into the WEB-INF/lib directory, all these files are available with sturts download.
    • struts2-core-2.0.11.1.jar
    • xwork-2.0.4.jar
    • freemarker-2.3.8.jar
    • commons-logging-1.1.1.jar
    • ognl-2.6.11.jar
  3. Update your web deployment desciptor to include the sturts filter dispatcher.
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>struts2Validation</display-name>
    <filter>
    <filter-name>struts2</filter-name>
    <filter-class>
    org.apache.struts2.dispatcher.FilterDispatcher
    </filter-class>
    </filter>
    <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>

    <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    </welcome-file-list>
    </web-app>
    WEB-INF/web.xml
  4. Create the input JSP
    <%@ taglib prefix="s" uri="/struts-tags"%>
    <html>
    <head>
    <title>Add Transaction</title>
    </head>
    <body>
    <s:form action="addTransaction" validate="true" method="post">
    <s:fielderror />
    <table>
    <tr>
    <td>Symbol</td>
    <td><s:textfield name="symbol"></s:textfield></td>
    </tr>
    <tr>
    <td>Type</td>
    <td><s:select name="type" list="#{'':'Select One', 'BUY':'Buy','SELL':'Sell','BUY_COVER':'Buy to Cover','SELL_SHORT':'Sell Short'}">
    </s:select></td>
    </tr>
    <tr>
    <td>Date</td>
    <td><s:textfield name="date" ></s:textfield></td>
    </tr>
    <tr>
    <td>Number of Shares</td>
    <td><s:textfield name="numberOfShares"></s:textfield></td>
    </tr>
    <tr>
    <td>Price</td>
    <td><s:textfield name="price"></s:textfield></td>
    </tr>
    <tr>
    <td>Commission</td>
    <td><s:textfield name="comission"></s:textfield></td>
    </tr>
    <tr>
    <td>Notes</td>
    <td><s:textfield name="notes"></s:textfield></td>
    </tr>
    <tr>
    <td colspan="2"> <s:submit name="submit" value="submit"></s:submit>
    <s:submit name="submitNoValidate" value="submit without validation" method="noValidation"></s:submit> </td>

    </tr>
    </table>
    </s:form>
    </body>
    </html>
    transactions.jsp

    Note: The method="noValidation" indicates to struts that on submission, the noValidation() method will be invoked on the AddTransactionAction class.
  5. Create the output JSP
    <%@ taglib prefix="s" uri="/struts-tags"%>
    <html>
    <head>
    <title>Transaction Added</title>
    </head>
    <body>
    <s:bean name="actions.AddTransactionAction" id="addTransaction" ></s:bean>
    <table>
    <tr>
    <td colspan="2">The following transaction has been added to your portfolio</td>
    </tr>
    <tr>
    <td>Symbol</td>
    <td><s:label name="symbol" value="%{symbol}" /></td>
    </tr>
    <tr>
    <td>Type</td>
    <td><s:label name="type" value="%{type}" />
    </td>
    </tr>
    <tr>
    <td>Date</td>
    <td><s:label name="date" value="%{date}"/></td>
    </tr>
    <tr>
    <td>Number of Shares</td>
    <td><s:label name="numberOfShares" value="%{numberOfShares}"></s:label></td>
    </tr>
    <tr>
    <td>Price</td>
    <td><s:label name="price" value="%{price}"></s:label></td>
    </tr>
    <tr>
    <td>Commission</td>
    <td><s:label name="comission" value="%{comission}"></s:label></td>
    </tr>
    <tr>
    <td>Notes</td>
    <td><s:label name="notes" value="%{notes}"></s:label></td>
    </tr>
    </table>
    </body>
    </html>
    done.jsp
  6. Create the Action class
    package actions;

    import org.apache.struts2.interceptor.validation.SkipValidation;

    import com.opensymphony.xwork2.ActionSupport;
    import com.opensymphony.xwork2.validator.annotations.RegexFieldValidator;
    import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
    import com.opensymphony.xwork2.validator.annotations.ValidatorType;
    import com.opensymphony.xwork2.validator.annotations.Validation;

    @Validation
    public class AddTransactionAction extends ActionSupport {

    private String symbol;
    private String type;
    private String date;
    private String numberOfShares;
    private String price;
    private String comission;
    private String notes;


    public String execute() throws Exception {
    System.out.println("In Execute");

    return SUCCESS;
    }

    @SkipValidation
    public String noValidation() throws Exception {
    System.out.println("In Novalidation");
    return SUCCESS;
    }


    public String getSymbol() {
    return symbol;
    }

    @RequiredStringValidator(type = ValidatorType.FIELD, message = "Symbol Required")
    public void setSymbol(String symbol) {
    this.symbol = symbol;
    }


    public String getType() {
    return type;
    }

    @RequiredStringValidator(type = ValidatorType.FIELD, message = "Type Required")
    public void setType(String type) {
    this.type = type;
    }


    public String getDate() {
    return date;
    }

    @RequiredStringValidator(type = ValidatorType.FIELD, message = "Date Required")
    @RegexFieldValidator(type=ValidatorType.FIELD, message="",key="date.error.message", expression = "[0-9][0-9]/[0-9][0-9]/[1-9][0-9][0-9][0-9]")
    public void setDate(String date) {
    this.date = date;
    }


    public String getNumberOfShares() {
    return numberOfShares;
    }


    @RequiredStringValidator(type = ValidatorType.FIELD, message = " Number of Shares Required")
    public void setNumberOfShares(String numberOfShares) {
    this.numberOfShares = numberOfShares;
    }


    public String getPrice() {
    return price;
    }

    @RequiredStringValidator(type = ValidatorType.FIELD, message = "Price Required")
    public void setPrice(String price) {
    this.price = price;
    }


    public String getComission() {
    return comission;
    }

    @RequiredStringValidator(type = ValidatorType.FIELD, message = "Comission Required")
    public void setComission(String comission) {
    this.comission = comission;
    }


    public String getNotes() {
    return notes;
    }


    public void setNotes(String notes) {
    this.notes = notes;
    }
    }
    AddTransactionAction.java

    Note:
    • The annotation @Validation is used to indicate that the current action might need validation. The validations on a method level can be skipped using the @SkipValidation annotation on the method.
    • The method noValidations() uses the @SkipValidation annotation, you can see this when you click on "Submit without validation" in the JSP
    • The @RequiredStringValidator annotation is used to indicate a Required Strint similar to the following xml rule
      <validators>
      <field name="numberOfShares">
      <field-validator type="requiredstring">
      <message>Number of Share is required</message>
      </field-validator>
      </field>
      </validators>
    • On the date field, I used a @RegexFieldValidator annotation, so that the date field will be mandated to have a given format.
    • Parameterized messages: You will notice that the message attribute of the @RegexFieldValidator is set to an empty string, while the key is set to a value. This is due to the fact that the message attribute is mandatory, and the key attribute is used to denote the message key from the properties files. The parameters can be retrieved in the properties files using the ${date} notation where the "date" variable is expected to available in the value stack
  7. Create a definition for the action in 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>
    <package name="struts2Validation" extends="struts-default">
    <action name="addTransaction"
    class="actions.AddTransactionAction">
    <result name="success">done.jsp</result>
    <result name="input">transactions.jsp</result>
    </action>
    </package>
    </struts>
    struts.xml

    Note: The result with name "input" is because the validator returns the result to input when validation fails.
  8. Create the properties file for messages
    date.error.message=Date ${date} is not properly formatted.
    package.properties

    Note: In the properties file, ${date} is used to retrieve the "date" value from the value stack, this is the way Struts 2 supports parameterization.

  9. Create the struts.properties file to set the theme to simple theme, so that you have more control how the UI components are laid out.
    struts.ui.theme=simple
    struts.properties

No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...