Struts 2 Jumpstart

December 28 20092 Commented

Categorized Under: Java

This tutorial is based on the following software environment.

Windows Vista Home Premium, Eclipse 3.5, JDK 1.6, Tomcat 6, Struts 2.1.8.1

MVC stands for Model View Controller architecture. In building complex enterprise level applications, MVC provides a clean separation between various components.

Model:-

Model represents data part of the application. All data access and business logic implementations are carried out at model layer. For eg, in a typical Employee database application, the employee information may be kept in RDBMS. All database operations using JDBC or any other framework are carried out at model layer. In Struts model is referred as actions.

View:-

View represents the presentation layer. For eg, a view representing employee list or an HTML form for creating employee record is a presentation component. In struts, view is represented by JSP, XSLT and other template engines like FreeMarker, Velocity etc.

Controller:-

 Controller is the major hub of MVC architecture. All requests are intercepted by controller which invokes appropriate model object and returns response. For eg, when a user request a list of employees, the controller invokes data access layer object and returns the output to browser. Servlets and Filters may be used as controller in Java web applications.

Struts widely use servlet filters to preprocess request and post process responses. They are called interceptors in struts. FilterDisptacher is an important filter which acts as the controller. All requests are handled by this filter, invoke appropriate actions and send response to user. In Struts 2.1 FilterDispatcher is deprecated and may use StrutsPrepareAndExecuteFilter. Struts uses a configuration file which represents mapping between action class, request and response. In between struts invokes various components, but description of these components is beyond the scope of this tutorial. Srtuts reduce the burden of developers by providing out of the box support for many recurring tasks in web application development like validation, exception handling, localization, file upload etc. It provides a rich set of tag libraries which is tightly integrated with framework and Java Server Pages.

Let us create a simple Hello World application in Struts.  Go to http://struts.apache.org/ and download Example Applications. Here I am using Struts 2.1.8.1 version. Unzip it into a convenient folder. Under this folder->apps there is a war file called struts2-blank-<version>.war. Unzip the war file. You may unzip it into same folder.

 struts_example_1

 Now let us get into Eclipse side. 

If you haven’t had Eclipse IDE with Tomcat , refer the following tutorial.

Installing and Configuring Eclipse with Tomcat in Windows

Open Eclipse. Java EE perspective is the default perspective. If you are not sure go to Window–>Open Perspective–>Other. Select Java EE and click OK.

Go to File–>New–>Dynamic Web project. Project Wizard appears. 

Give the project name as StrutsExample. All other options do not require modification if you are using Eclipse with Tomcat as server. If you have configured multiple servers you may change the target run-time. Click Finish button. Now we have to add the project under server. Go to server window, right click on server entry and select Add and Remove. Move the project from left to right window in properties box. Click Finish button.

Now we have to add Struts libraries to our application. Open the directory in which we extracted Struts blank application. Go to WEB-INF->lib and copy all jar files.

struts_example_2

Go to Eclipse and paste under WebContent->WEB-INF->lib folder. All third party libraries are put under WEB-INF/lib folder in a typical web application. Alternatively you may put the jar files in Tomcat class-path folder lib also.

struts_example_3

Now open the web.xml file located under WEB-INF folder. Add the following XML snippet just after <display-name> element and save the file.

<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>

We have to create Struts configuration file. Right click on src folder and create xml file. Select the parent folder as src and give the file name as struts.xml. Press Finish button.

struts_example_3

Now replace the content of xml file with the following XML snippet.

<?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="example" namespace="/" extends="struts-default">
		<action name="HelloWorld" class="example.HelloWorld">
			<result>/HelloWorld.jsp</result>
		</action>
	</package>
</struts>

Save the file. Now let us create a JSP file. Right click on WebContent in Project Explorer and create JSP file. Give the file name as HelloWorld.jsp Press Finish button.

struts_example_4

Replace the content with the following lines of code.

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
    <title>Hello World</title>
</head>
<body>
<h2><s:property value="message"/></h2>
</body>
</html>

Save the file. The last step in our example is to create an action class. Right click on src folder and create new class. Give the package name as example and class name as HelloWorld. Press finish button. Replace the content with the following snippet of code.

package example;
 
import com.opensymphony.xwork2.ActionSupport;
 
public class HelloWorld extends ActionSupport {
 
	private String message;
 
	public String execute() throws Exception{
		this.setMessage("Hello World");
		return SUCCESS;
	}
 
 
	public String getMessage() {
		return message;
	}
 
	public void setMessage(String message) {
		this.message = message;
	}
 
}

Save the file. Now go to server window in Eclipse and start the server. Open the browser, enter the following url and hit enter.

http://localhost:8080/StrutsExample/HelloWorld

If you could see the Hello World message, congratulations! You have finished your first step towards one of the most popular Java web application framework. Now let us walk through the code.

In web.xml we added reference for filter StrutsPrepareAndExecuteFilter. This filter is applied to all incoming requests which is specified in servlet-mapping section. It prepares and execute Struts dispatching process. In struts.xml configuration file, we define a package named example. This is used to logically group all related action classes, interceptors, results etc. The package extends struts-default which means all elements defined in struts-default package are available in example package also. struts-default package contains many struts specific interceptors, bean classes etc. The namespace is the relative path to application URI. Here it is defined as / which means requests coming under root context path. Under package element, we define an action named HelloWorld and corresponding class is example.HelloWorld. The result of this action is defined as HelloWorld.jsp file. The result tag defines two optional attributes. The name represents the token of the string returned by action class. For eg, the action class may return “success”, “error” etc. The default name is “success”. The default result type is “dispatcher” which redirects to a JSP, template etc where the target resource gets same request/response pair. When a user requests HelloWorld, Struts looks in configuration file and corresponding action class is invoked. In our case it is HelloWorld class defined in example package. The HelloWorld is a simple bean class with one property named message, getter and setter methods. It implements a method called execute() which is the default method invoked by Struts in any action class. In execute() method we set the value of message property as “Hello World” and returns SUCCESS which is a constant with value “success”. According to our configuration in struts.xml, on returning “success” it is redirected to HelloWorld.jsp page. In JSP page it uses struts tag libraries which is defined using taglib directive and show the value of message property using property tag.

cheers,

2 Responses to “Struts 2 Jumpstart”

  1. Zack says:

    Finaly an example well and cearly explaned.

  2. Suman says:

    Wonderful explanation! Thanks

Leave a Reply

*