Tuesday, 18 June 2013

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 (register), with ActionSupport classes (RegisterAction.java), 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 Student whose name and age would be captured using a simple page and we will put two validation to make sure that use always enters a name and age should be in between 5 and 15.

Create a Dynamic Web Project :

Step: 1

Start your Eclipse and then go with File > New > Dynamic Web Project and enter project name
as Struts2Annotations and set rest of the options as given in the following screen :


I have used Tomcat v7.0 as server. (as mention in the Image in Target Runtime). You can set it here or set at later stage before running the application.

Go to next screen by clicking the Next Button. Select all default options and finally check Generate Web.xml deployment descriptor option.

After Clicking the Finish Button, the Project Explorer window will look like




Step : 2

We need to include some necessary jars into the lib folder.
Path in My Eclipse : WebContent/WEB-INF/lib
  • 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

Step: 3

Create the main page (index.jsp)

Lets create a jsp page (index.jsp) inside webcontent folder. 
To create this jsp, Right click on Webcontent folder => New=>Jsp File

Give the File name as index.jsp => Finish

This page will used to collect Student information such as Name & Age



index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome Page: Register Form</title>
</head>
<body>
<s:form action="register">
<s:textfield label="Name" name="name" size="20" />
<s:textfield label="Age" name="age" size="20" />
<s:submit label="submit" align="center" />
</s:form>
</body>
</html>

Step : 4

success.jsp

In the Same method we have to create another view (success.jsp) inside the webcontent folder.
This page invokes when action returns “success”.

Code:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Success</title>
</head>
<body>
Student Information is captured successfully.
</body>
</html>


Step: 5

Create Action Class:

Action class is the key to Struts 2 application and we implement most of the business logic in action class. So let us create a java file RegisterAction.java under Java Resources => src with a package name com.mind.struts2 .

Right click on src => New = > Package

Type com.mind.struts2 in the Name field & then Finish


After the package is created, Right click on the package (from left : project explorer) => New = > class



The Action class responds to a user action when user clicks a URL. One or more of the Action class's methods are executed and a String result is returned. Based on the value of the result, a specific JSP page is rendered.

Add the following code to RegisterAction.java class

RegisterAction.java

package com.mind.struts2;

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.RequiredStringValidator;

/**
* Annotation Used in this Class. So no need to create struts.xml
*/

/**
*The @Results annotation defines a set of results for an Action.
*@Result annotation allows the definition of Action results in the Action class
*/
@Results({
@Result(name="success", location="/success.jsp"),
@Result(name="input", location="/index.jsp")
})

public class RegisterAction extends ActionSupport{
private static final long serialVersionUID = 464297287787119149L;
private String name;
private int age;

/**
* The @Action annotation tells Struts 2 to execute the annotated method when the action link value equals the Action annotation's value ("register").
*/
@Action(value="/register")
public String execute()
{
return SUCCESS;
}

/**
* This annotation checks that a String field is not empty(i.e. non-null with a length > 0).
*/
@RequiredStringValidator( message = "The name is required" )
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

/**
* This validation annotation checks that a numeric field has a value within a specified range. If neither min nor max is set, nothing will be done.
*/
@IntRangeFieldValidator(message = "Age must be in between 5 and 15",
min = "5", max = "15")
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}


Step: 6

Configuration File (web.xml)

Web.xml file is an entry point for any request to Struts 2. This file needs to be present under
WEB-INF folder. Eclipse already created a web.xml file. We just to modify that file.

web.xml


<?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_3_0.xsd"
id="WebApp_ID" version="3.0">

<display-name>Struts 2</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
<init-param>
<param-name>struts.devMode</param-name>
<param-value>true</param-value>
</init-param>
</filter>

<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

Step: 7

Execute the Application

To run this application, Right click on Project (Struts2Annotations : from project explorer) => Run As => Run on Server.


Here you can configured a new server. But in our application we configured it first.

After the server Started, the project automatically deployed in the server.

Now you can browse this url :

http://localhost:8080/Struts2Annotations/index.jsp
8080 : default tomcat port

Output: 


Thank You