Struts2 - Step by step guide for the programmers

This tutorial explains struts 2 with the bare minimum. You won't get lost in the unwanted files under the struts example applications.

Pre-requisites for this struts2 tutorial

You should be comfortable working with eclipse and WTP. I have used eclipse 3.2.2 myself. Any 3.1 or latter should work, although not tested. You will also need web Tools plugins from the curresponding Calisto release.

Developing the the struts2 “helloworld ” with out any classes

Setting up the stage

  1. Create a eclipse project named “HelloWorld”.
  2. From eclipse select File -> New -> Project and from the list select “Dynamic Web Project” under the “Web” Group.

  3. Give the project name as “HelloWorld”.
  4. Under the “target runtime” select Tomcat 5.5 instance. Click Finish to go back to the workspace.
  5. Now create a file called “index.jsp” inside “WebContent” folder with the following content

<%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Hello World !</title>
</head>
<body>
    <h1> Struts 2 Hello World </h1>
</body>
</html>

Now if you select run “index.jsp” using “run on the server” option, you can see the JSP page we just created. If you see that, congratulations, we are ready to go to the struts2 tutorial.

Integrating Struts2

At the minimum struts2 requires 4 jar files, and the configuration file “struts.xml”. We also need to make some modification to the project's build settings, so that eclipse will put the class files under “WebContent/classes”. If you know how to do that go ahead and do it. If you don't know, here is how it is done.

  1. Rght click on the project and select 'Properties'.
  2. Select 'Java Build Path ' option on the left pan of the properties window.
  3. Under the 'Source' tab you can see 'HollowWorld/src' already listed as the source folder. Bottum of the same sheet displays the current value of the out put folder. Change that to 'HelloWorld/WebContent/classes'.
  4. Click OK.

Now we need to add the struts 2 jar files to the Web app libray. Copy the following files from struts distribution to the “WebContent/WEB_INF/lib” folder.

  1. commons-logging
  2. freemarker
  3. ognl
  4. struts2-core
  5. xwork

I didn't mention the version number because it may change. But make sure you copy everything from the struts example application that comes with the struts distribution.

Now we need to add the struts 2 filter and filter mapping to the web.xml. Add the following line to your web.xml.

<!-- add filter just after the displaname property or after other filters. -->
 <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
    </filter>
   <!-- Add the filter mapping after all filters -->
     <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

Create a files “struts2.xml” under 'HelloWorld/src' and add the following content.

<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="default" extends="struts-default">
    </package>
</struts>

This is the minimum required configuration for struts. Now if you restart tomcat, you should be able to see the same index.jsp page. Now add the following snippets between the package tags.

<action name="HelloWorld">
            <result>helloWorld.jsp</result>
        </action>

Create a file called helloWorld.jsp under 'WebContent' folder.
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<!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=UTF-8">
<title>helloWorld.jsp</title>
</head>
<body>
<h1><span style="color:green"> Hello World from struts2 ! </span></h1>
</body>
</html>

After restarting tomcat, try accessing '/HelloWorld/HelloWorld.action' , you can see the 'Hello world from struts2!” message on the screen. So your first action worlked, even though you didn't write any !

Moving on to struts2 Action classes.

The Greeting Application.

When a request comes to the container, it checks web.xml to decide how it should be dispatched. Here is the web.xml for our “Greeting” Application

  1. <web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  2.     <display-name>Struts2 Test </display-name>
  3.     <filter>
  4.         <filter-name>struts2</filter-name>
  5.         <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
  6.     </filter>
  7.     <filter-mapping>
  8.         <filter-name>struts2</filter-name>
  9.         <url-pattern>/*</url-pattern>
  10.     </filter-mapping>
  11.     <welcome-file-list>
  12.                 <welcome-file>index.html</welcome-file>
  13.         </welcome-file-list>
  14. </web-app>

On line numbers 3-6 , we are enabling struts2 filter. We map this filter to all urls on line numbers 7 through 10.ie all requests are passed through struts2 FilterDispatcher. The dispatcher looks in to the struts2.xml file for any matching mappings. Here is our struts2.xml.

  1. <!DOCTYPE struts PUBLIC
  2.     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
  3.     "http://struts.apache.org/dtds/struts-2.0.dtd">
  4. <struts>
  5. <package name="default" extends="struts-default">
  6.                 <action name="HelloWorld">
  7.                         <result>helloWorld.jsp</result>
  8.                 </action>
  9.                 <action name="Greet" class="org.techienet.tutorials.struts2.helloworld.Greet">
  10.                         <result name="greet">/greet.jsp</result>
  11.                 </action>
  12.         </package>
  13. </struts>

line # 6-8 creates the HelloWorld Action (HelloWorld.action), that we used in the previous example. But we didn't give any class attribute to the action tag. if no class is defined for an action, struts assumes the action returns “SUCCESS”. We 'll discuss about the return values later. The Greeting action (Greet.action) is configured on line # 9 through 11. In this case we are giving a class attribute, meaning , we are going to create our own class for this action.

Now Let's try creating a struts2 Action class. Usually we sub class ActionSupport for creating our own Action class. Here is the code.

  1. package org.techienet.tutorials.struts2.helloworld;
  2. import com.opensymphony.xwork2.ActionSupport;
  3. @SuppressWarnings("serial")
  4. public class Greet extends ActionSupport {
  5.         private String message =null;
  6.         public String execute() throws Exception {
  7.                 setMessage("Welcome to Struts2 Actions !");
  8.                 return "greet";
  9.         }
  10.         public String getMessage() {
  11.                 return message;
  12.         }
  13.         public void setMessage(String message) {
  14.                 this.message = message;
  15.         }
  16. }

When struts finds “class” attribute for an action mapping, it create an instance of the class, and invokes it's execute method. In our action class we have one property apart from the execute method. In the execute method we are setting this property, to the greeting message. We can access this property from the jsp file using the tag library suplied by the struts2 package.

Note the value that we are returning from the execute method. it's the string "greet" !!!. On line number 10 of the struts2.xml we are configuring a result with the same name. that's what is telling struts to pick up the file "/greet.jsp" and merge it to the response.

Pretty Simple , Eh ?

Here is our "/greet.jsp".

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2.     pageEncoding="UTF-8"%>
  3. <%@ taglib uri="/struts-tags" prefix="s"  %>
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"  "http://www.w3.org/TR/html4/loose.dtd">
  5. <html>
  6. <head>
  7. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  8. <title>Insert title here</title>
  9. </head>
  10. <body>
  11. <h1> Hello World ! , through Action ...</h1>
  12. <s:property value="message"/>
  13. </body>
  14. </html>

manning

action class