Annotations in Struts2 with an Example

We can achieve Zero Configuration in struts2 using java 5 annotations feature. Previously we normally configured struts.xml for all the configurations . The XML file wires up the action names (employee), with ActionSupport classes (, and with the result to render back to the browser (success.jsp). Struts 2 provides an alternative to using XML to configure your application by using standard naming conventions and annotations for your action names, ActionSupport classes, and results.
We will use annotations in a small example and it is being developed in Eclipse.

Here we will take an example of Employee whose name, emailid, age and telephone would be captured using a simple page and we will put two validation to make sure that use always enter a name , a emailid and a telephone and age should be in between 18 and 65.

To start using annotations in your project, make sure you have included following jar files in your WebRoot/WEB-INF/lib folder:
  • struts2-convention-plugin-x.y.z.jar
  • asm-x.y.jar
  • asm-commons-x.y.jar
  • antlr-x.y.z.jar
  • commons-fileupload-x.y.z.jar
  • commons-io-x.y.z.jar
  • commons-lang-x.y.jar
  • commons-logging-x.y.z.jar
  • commons-logging-api-x.y.jar
  • freemarker-x.y.z.jar
  • javassist-.xy.z.GA
  • ognl-x.y.z.jar
  • struts2-core-x.y.z.jar
  • xwork-core.x.y.z.jar

Create main page:
Let us write main page JSP file employee.jsp, which will be used to collect Employee related information mentioned above.
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<title><s:property value="getText('global.form')" /> - Struts2 Demo |</title>
<s:head />
<h2><s:property value="getText('global.form')" /></h2>
<s:form action="employee" method="post" validate="true" >
    <s:textfield name="name" key="" size="20"/>
    <s:textfield name="age" key="global.age" size="20" />
    <s:textfield name="email" key="" size="20" />
    <s:textfield name="telephone" key="global.telephone" size="20" />
    <s:submit name="submit" key="global.submit" align="center" />

<s:url id="localeEN" namespace="/" action="locale" >
   <s:param name="request_locale" >en</s:param>
<s:url id="localeHN" namespace="/" action="locale" >
   <s:param name="request_locale" >hn</s:param>
<s:url id="localeES" namespace="/" action="locale" >
   <s:param name="request_locale" >es</s:param>
<s:url id="localezhCN" namespace="/" action="locale" >
   <s:param name="request_locale" >zh_CN</s:param>
<s:url id="localeDE" namespace="/" action="locale" >
   <s:param name="request_locale" >de</s:param>
<s:url id="localeFR" namespace="/" action="locale" >
   <s:param name="request_locale" >fr</s:param>
<s:a href="%{localeEN}" >English</s:a>
<s:a href="%{localeHN}" >Hindi</s:a>
<s:a href="%{localeES}" >Spanish</s:a>
<s:a href="%{localezhCN}" >Chinese</s:a>
<s:a href="%{localeDE}" >German</s:a>
<s:a href="%{localeFR}" >France</s:a>
Create Views:
We will use JSP file success.jsp which will be invoked in case defined action returns SUCCESS.
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<title><s:property value="getText('global.form')" /> - Struts2 Demo |</title>
    <h2><s:property value="getText('global.success')" />.</h2>
Create Action:
This is the place where annotation will be used. Let us re-define action class Employee with annotation, and then add a method called validate() as shown below in file. Make sure that your action class extends the ActionSupport class, otherwise your validate method will not be executed.

package com.dineshonjava.struts2.action;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.validator.annotations.IntRangeFieldValidator;
import com.opensymphony.xwork2.validator.annotations.RequiredFieldValidator;

 * @author Dinesh Rajput
 @Result(name="success", location="/success.jsp"),
 @Result(name="input", location="/employee.jsp")
public class EmployeeAction extends ActionSupport {

 private static final long serialVersionUID = 1L;
 private String name;
    private Integer age;
    private String email;
    private String telephone;
    public String addEmployee() {
        return SUCCESS;
    @RequiredFieldValidator( message = "The name is required" )
 public String getName() {
  return name;
 public void setName(String name) { = name;
  @IntRangeFieldValidator(message = "Age must be in between 28 and 65",
             min = "18", max = "65")
 public Integer getAge() {
  return age;
 public void setAge(Integer age) {
  this.age = age;
 @RequiredFieldValidator( message = "The email is required" )
 public String getEmail() {
  return email;
 public void setEmail(String email) { = email;
 @RequiredFieldValidator( message = "The phone is required" )
 public String getTelephone() {
  return telephone;
 public void setTelephone(String telephone) {
  this.telephone = telephone;

We have used few annotations in this example. Let me go through them one by one:
  • First, we have included the Results annotation. A Results annotation is a collection of results. Under the results annotation, we have two result annotations. The result annotations have the name that correspond to the outcome of the execute method. They also contain a location as to which view should be served corresponding to return value from addEmployee().
  • The next annotation is the Action annotation. This is used to decorate the addEmployee() method. The Action method also takes in a value which is the URL on which the action is invoked.
  • Finally, I have used two validation annotations. I have configured the required field validator on name field and the integer range validator on the age field. I have also specified a custom message for the validations.

Configuration Files:
We really do not need struts.xml configuration file, so let us remove this file and let us check the content of web.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="" xmlns="" xmlns:web="" xsi:schemaLocation="" id="WebApp_ID" version="3.0">
Now, right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat's webapps directory. Finally, start Tomcat server and try to access
URL http://localhost:8080/doj/employee.jsp.

This will give you following screen:
Employee error page because of validation fails

Employee page on success

Download Source Code

<<Previous <<   || Index ||   >>Next >>

No comments:

Post a Comment