Meyyappan has posted 101 posts at DZone. View Full User Profile

Struts 2 Annotation Tutorial 1

06.14.2012
| 31198 views |
  • submit to reddit

We will learn annotations in struts 2 using the hello user example. In this example we will get the user name and display a welcome message to the user. There are two versions of this example, in the first one we will see how to do this by using the intelligent defaults provided by the struts 2 framework. We will not do any configuration in this example except the deployment descriptor.

The example is created using ecilpse. The war file of this example is also provided at the end of this tutorial so that you can try it yourself.

So lets start, you need to have the following jar files in the WEB-INF/lib directory.

commons-fileupload-1.2.1
commons-io-1.3.2
commons-logging-1.1
freemarker-2.3.13
junit-3.8.1
ognl-2.6.11
spring-test-2.5.6
struts2-convention-plugin-2.1.6
struts2-core-2.1.6
xwork-2.1.2

You can definitely save a lot of time by having the correct versions of these jar files in the lib directory. The struts2-convention-plugin-2.1.6 jar file is needed if your are using annotations.

This is the directory structure of the hello user example.

Now we will create the index page. This page is simple, we use the struts tags to create the page. The textfield tag is used to create the textfiled and the submit tag is used to create the submit button. The index.jsp page contains the following 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">
<%@taglib uri="/struts-tags" prefix="s" %>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Hello World</title>
    </head>
    <body>
        <s:form action="welcome-user" >
            <s:textfield name="userName" label="User Name" />
            <s:submit />
        </s:form>
    </body>
</html>

Note the URL value of the action attribute in the form tag. In the end we will see how everything relates together.

We compose the welcome message in the execute() method of the WelcomeUser class and we return "success". The WelcomeUser class contains the following code.

package com.vaannila.action;

import com.opensymphony.xwork2.ActionSupport;

public class WelcomeUser extends ActionSupport{
    private String userName;
    private String message;

    public String execute() {
            message = "Welcome " + userName;
            return SUCCESS;
    }

    public void setUserName(String userName) {
            this.userName = userName;
    }

    public void setMessage(String message) {
            this.message = message;
    }

    public String getUserName() {
            return userName;
    }

    public String getMessage() {
            return message;
    }
}

Note the class name, can you find any similarities between the action URL and the class name? if yes got the concept, if no don't worry you will learn what it is in the coming pages.

We display the welcome message to the user using the welcome-user.jsp page. The content of the page is very simple, we just display the message. The important thing to note here is the name of the page.

<%@ 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>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome User</title>
</head>
<body>

<h1>${message}</h1>

</body>
</html>

Now we will configure the web.xml for the struts 2 framework. We need to specify the filter and the filter mapping here. Except this there is no need to have any other XML configuration files.

<?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>Struts2Example1</display-name>

   <filter>
		<filter-name>struts2</filter-name>
		<filter-class>
			org.apache.struts2.dispatcher.ng.filter. StrutsPrepareAndExecuteFilter
        </filter-class>
	</filter>

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

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

</web-app>

Now the coding part is complete. You can run the example by using the following URL "http://localhost:8080/Struts2Example1/"

Enter a user name and submit the form, you will see the following welcome-user.jsp page.

The example works fine. Now lets see how the example works.

The Convention plug-in is the one which does everything in the background. The Convention plug-in does the following things.

  • By default the Convention plug-in looks for the action classes inside the following packages strut, struts2, action or actions. Here our package name is com.vaannila.action. Any package that matches these names will be considered as the root package for the Convention plug-in.
  • The action class should either implement com.opensymphony.xwork2.Action interface or the name of the action class should end with Action. Here we extend our WelcomeUser class from com.opensymphony.xwork2.ActionSupport which inturn implements com.opensymphony.xwork2.Action.
  • The Convention plug-in uses the action class name to map the action URL. Here our action class name is WelcomeUser and the URL is welcome-user. The plug-in converts the camel case class name to dashes to get the request URL.
  • Now the Convention plug-in knows which Action class to call for a particular request. The next step is to find which result to forward based on the return value of the execute method. By default the Convention plug-in will look for result pages in WEB-INF/content directory.
  • Now the Convention plug-in knows where to look for results, but it doesn't know which file to display inside the content directory. The Convention plug-in finds this with the help of the result code returned by the Action class. If "success" is returned then the Convention plug-in will look for a file name welcome-user-success.jsp or welcome-user.jsp . It need not be a jsp file it can be even a velocity or freemaker files. If the result value is "input" it will look for a file name welcome-user-input.jsp or welcome-user-input.vm or welcome-user-input.ftl.
  • For more Struts 2 annotations example refer here ( Struts 2 Annotations - Part 2 ).

You can download the Struts 2 annotation example by clicking the download link below.

Source :Download

Source + Lib :Download 

Published at DZone with permission of its author, Meyyappan Muthuraman.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags:

Comments

Zitao Dong replied on Tue, 2013/12/17 - 1:41am

" By default the Convention plug-in looks for the action classes inside the following packages strut, struts2, action or actions."

"strut" above should be "struts".

Aashish Dalmia replied on Wed, 2014/01/15 - 6:17pm

 Awesome convention-plugin and struts 2 concept man!!

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.