View RSS Feed

Struts

Building your first Struts 2 application using Eclipse

Rating: 3 votes, 2.33 average.
by , 12-09-2011 at 04:30 PM (18571 Views)
Struts is one of the most popular web framework for Java. It comes with 2 major branches, Struts 1 and Struts 2. Both implement MVC architecture but Struts 2 is much simpler, easier to build, deploy and maintain than Struts 1.
This article will guide you through the steps to build a simple Struts 2 application using Eclipse IDE.

Download Struts 2 and required libraries

Download latest version of Struts 2 from Download a Release
Select the full distribution, struts-2.2.3.1-all.zip
Extract the zip file into a directory on your hard drive, says struts-2.2.3. Look at the folder “lib”, you will see there are many JAR files there, but for a simple hello world Struts 2 application, we need only a smaller number of them.

Create a Java web project

Go to File -> New -> Project… In the dialog New Project, select Web -> Dynamic Web Project.

Name:  new project 1.PNG
Views: 9101
Size:  21.3 KB
Figure: The New Project dialog

Click Next, in the New Dynamic Web Project dialog, type project name, “HelloStruts2”, leave other fields as default, then click Next:

Name:  new project 2.PNG
Views: 8963
Size:  26.8 KB
Figure: The New Dynamic Web Project screen

In the next screen, “Project Facets”, select version “2.4” for “Dynamic Web Module” and version “5.0” for “Java”, as shown in the screen below:

Name:  new project 3.PNG
Views: 8914
Size:  26.3 KB
Figure: Select versions

Click Finish, Eclipse will create a skeleton for the project HelloStruts2. Create a package com.mycompany under “Java Resources: src”:

Name:  project explorer 2.PNG
Views: 8977
Size:  14.1 KB
Figure: Structure of the newly created project

Copy the following JAR files from directory struts-2.2.3\lib that you have extracted before, to the directory WebContent\WEB-INF\lib under the project’s root:


  1. commons-fileupload-1.2.2.jar
  2. commons-io-2.0.1.jar
  3. commons-lang-2.5.jar
  4. freemarker-2.3.16.jar
  5. javassist-3.11.0.GA.jar
  6. ognl-3.0.1.jar
  7. struts2-core-2.2.3.jar
  8. xwork-core-2.2.3.jar





Configure Struts 2’s action Servlet

In order to have Struts intercepts all requests coming to the application, we need to configure a filter in the deployment descriptor. Open web.xml file under WebContent\WEB-INF, add the following XML lines:

XML Code: Configuration for Struts in web.xml
    
    <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>
Configure Struts 2 configuration

By default, upon initialization, Struts will look for a configuration file called struts.xml in the application’s classpath. Through the configuration file, you tell how Struts maps between the controller (Action class) and the view (JSP page). Create the struts.xml file under “Java Resources: src” directory, and paste the following code:

XML Code: The Struts configuration file
<?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="main" extends="struts-default">
        <action name="hello" class="com.mycompany.HelloAction"
            method="sayHello">
            <result name="success">/hello.jsp</result>
        </action>
    </package>
   
</struts>
In Struts 2, we can group related actions into a package. In the above configuration we define a package “main” and have it extends the Struts’ base package, “struts-default”. In this package, we declare an action “hello” with some interesting stuffs:

  • The name attribute specifies the action name, which is also the URL pattern that Struts will intercept.
  • The class attribute points to a Java class which we will create in the next step. This class is the action class, or the controller. When a request having the URL ends with “hello”, this action class will be picked up by the framework and invoke the method defined in the attribute “method”.
  • The method attribute specifies the method of the action class that will be invoked.



The sub element “result” inside the action specifies a logical mapping to a JSP page (view):

The name attribute specifies the name of the view. The action class method should return a String matching a view name.
The /hello.jsp is the actual JSP page that will render the view for action “hello”.


So far we can understand the configuration in a natural way: When a request having the pattern “hello” comes in, an instance of class com.mycompany.HelloAction is created, and its method “sayHello” will be invoked. The action can pick up a view named “success” to render response, the view actually maps to the hello.jsp page.

Implement the controller

Next, we should implement an action class that matches the configuration above. The source code looks like the following:

Java Code: Code of the controller class
package com.mycompany;

import com.opensymphony.xwork2.ActionSupport;

public class HelloAction extends ActionSupport {
    private String message;
   
    public String sayHello() {
        message = "Hello World, Struts 2!";
        return SUCCESS;
    }

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

    public String getMessage() {
        return message;
    }
}
The HelloAction class extends ActionSupport class and implements a method “sayHello” and a property “message”. The sayHello method simply assigns a String “Hello World, Struts 2!” to the variable “message”, then returns a String constant, SUCCESS. This constant matches the view’s name defined in the struts.xml file. The member variable message has appropriate getter and setter methods which can be used by the view to access its content.

Write the view

Next, we create a hello.jsp file under WebContent directory. The code of hello.jsp file looks like this:

XML Code: Code of the hello.jsp page
<%@ 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>Struts 2</title>
</head>
<body>
<h2><s:property value="message" /></h2>
</body>
</html>
It is a pretty simple JSP file. There are two lines you should be noticed:

  • <%@ taglib prefix="s" uri="/struts-tags" %>: instructs the container that the page is using Struts 2’s custom tags.
  • <h2><s:property value="message" /></h2>: use the <s:property /> tag to print out the value of the variable “message” which is defined by the action class.


So the page simply displays a text message that is set by the action class, “Hello World, Struts 2!”;

Setup server runtime

So far we have built all the basics: web.xml configuration file, struts.xml configuration file, HelloAction class and hello.jsp page. It’s time to set up a server to run the application. Suppose you have Tomcat 6.0 installed on your computer.

Right click in Eclipse’s Servers tab, select New -> Server:

Name:  new server 1a.PNG
Views: 8846
Size:  6.7 KB
Figure: Create a new server in Servers view

In the New Server dialog, open the branch “Apache” and select “Tomcat v6.0 Server”, click Next.
In the next screen, click Browse to select Tomcat’s installation directory on your computer:

Name:  new server 3a.PNG
Views: 8878
Size:  42.5 KB
Figure: Selection Tomcat's installation directory

Click Finish. In the screen “Add and Remove Projects”, select the project HelloStruts2 on the column “Available projects”, then click Add to add the project to the column “Configured projects”, then click Finish.

Name:  new server 6.PNG
Views: 8849
Size:  22.5 KB
Figure: Add the project HelloStruts2 to Tomcat

Now the HelloStruts2 application is deployed on Tomcat server.

Name:  new server added a.PNG
Views: 8828
Size:  7.7 KB
Figure: New server added with the configured project

Running the application

Now we are ready to start the server and run the hello world Struts 2 application. Right click on the server node in tab Servers, click Start:

Name:  start server.PNG
Views: 8846
Size:  17.6 KB
Figure: Start the server

Look at the Console tab, you will see some logging information outputted when the server starts and Struts initializes.
Type the following URL into your browser’s address bar (your server’s port may be different):
http://localhost:9898/HelloStruts2/hello
If everything is working fine, the server should return this page:

Name:  running app.PNG
Views: 8867
Size:  68.0 KB
Figure: Running the Struts 2 application

So far we have built, deployed and run a simple Struts 2 web application. I hope this article will be helpful for those who are starting to learn Struts 2.

Submit "Building your first Struts 2 application using Eclipse" to Facebook Submit "Building your first Struts 2 application using Eclipse" to Digg Submit "Building your first Struts 2 application using Eclipse" to del.icio.us Submit "Building your first Struts 2 application using Eclipse" to StumbleUpon Submit "Building your first Struts 2 application using Eclipse" to Google

Categories
Eclipse , Struts

Comments