Creating the first application using Struts 2

By: Gokul Verma Emailed: 1607 times Printed: 2078 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

Suppose you want to create a simple "Hello World" example that displays a welcome message use the blank web application in the distribution's apps directory is meant as a template. We can make a copy of the "blank.war", deploy it to our container, and use the exploded copy as the basis for our application. There is even a simple batch file in the source code directory that we can use to recompile the application in place.

When you submit a HTML form to the framework, the input is not sent to another server page, but to a Java class that you provide. These classes are called Actions. After the Action fires, a Result selects a resource to render the response. The resource is generally a server page, but it can also be a PDF file, an Excel spreadsheet, or a Java applet window.

  1. Create a server page to present the messages
  2. Create an Action class to create the message
  3. Create a mapping to couple the action and page
    •  
    By creating these components, we are separating the workflow into three well-known concerns: the View, the Model, and the Controller. Separating concerns makes it easier to manage applications as they become more complex.

    Let's look at an example Action, server page, and mapping. If you like, fire up your IDE, and enter the code as we go.

The Code

First, we need a server page to present the message.

HelloWorld.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>

<html>
    <head>
        <title>Hello World!</title>
    </head>
    <body>
        <h2><s:property value="message" /></h2>
    </body>
</html>

Second, we need an Action class to create the message.

HelloWorld.java
package tutorial;
import com.opensymphony.xwork2.ActionSupport;
public class HelloWorld extends ActionSupport {

    public static final String MESSAGE = "Struts is up and running ...";

    public String execute() throws Exception {
        setMessage(MESSAGE);
        return SUCCESS;
    }

    private String message;

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

    public String getMessage() {
        return message;
    }
}

Third, we need a mapping to tie it all together.

Edit the struts.xml file to add the HelloWorld mapping.

struts.xml
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <package name="tutorial" extends="struts-default">
        <action name="HelloWorld" class="tutorial.HelloWorld">
            <result>/HelloWorld.jsp</result>
        </action>
        <!-- Add your actions here -->
    </package>
</struts>

Go ahead and try it now! Deploy the application and open http://localhost:8080/tutorial/HelloWorld.action and see what happens! You should see a page with the title "Hello World!" and the message "Struts is up and running!".

  •  
Don't forget

Compile your Action to WEB-INF/classes and restart your container if necessary. If you are using maven, you can just run:

> mvn jetty:run

How the Code Works

Your browser sends to the web server a request for the URL http://localhost:8080/tutorial/HelloWorld.action.

  1. The container receives from the web server a request for the resource HelloWorld.action. According to the settings loaded from the web.xml, the container finds that all requests are being routed to org.apache.struts2.dispatcher.FilterDispatcher, including the *.action requests. The FilterDispatcher is the entry point into the framework.

  2. The framework looks for an action mapping named "HelloWorld", and it finds that this mapping corresponds to the class "HelloWorld". The framework instantiates the Action and calls the Action's execute method.
  3. The execute method sets the message and returns SUCCESS. The framework checks the action mapping to see what page to load if SUCCESS is returned. The framework tells the container to render as the response to the request, the resource HelloWorld.jsp.
  4. As the page HelloWorld.jsp is being processed, the <s:property value="message" /> tag calls the getter getMessage of the HelloWorld Action, and the tag merges into the response the value of the message.
  5. A pure HMTL response is sent back to the browser.

Testing Actions

Testing an Action is easy. Here's a test for our Hello World Action.

HelloWorldTest.java
package tutorial;
import junit.framework.TestCase;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;

public class HelloWorldTest extends TestCase {
  public void testHelloWorld() throws Exception {

    HelloWorld hello_world = new HelloWorld();
    String result = hello_world.execute();

    assertTrue("Expected a success result!",
      ActionSupport.SUCCESS.equals(result));

    assertTrue("Expected the default message!",
      HelloWorld.MESSAGE.equals(hello_world.getMessage()));

    }
}

What to Remember

The framework uses Actions to process HTML forms and other requests. The Action class returns a result-name such as SUCCESS, ERROR, or INPUT. Based on the mappings loaded from the struts.xml, a given result-name may select a page (as in this example), another action, or some other web resource (image, PDF).

When a server page is rendered, most often it will include dynamic data provided by the Action. To make it easy to display dynamic data, the framework provides a set of tags that can be used along with HTML markup to create a server page.


Struts Home | All Struts Tutorials | Latest Struts Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(11)


1. View Comment

Please provide web.xml for the example

View Tutorial          By: Amit at 2008-12-24 02:16:59
2. View Comment

Hi,
I done very simple, just copy the struts2-blank-2.0.14.war and past into tomcat webapps folder. It deploy automatically but i could able to run properly.
The error i was got
type Status report
message /struts2-blank-2.0.14/
description The requested resource (/struts2-blank-2.0.14/) is not available.

Please could you tell me, any changes i have to do

thanks
Sri


View Tutorial          By: sridhar at 2009-03-01 19:17:10
3. View Comment

Please provide web.xml file for this example

View Tutorial          By: Girish at 2009-03-08 22:53:03
4. View Comment

Good hello world to start with struts2 provided you provide web.xml.

View Tutorial          By: Boby Thomas at 2009-04-01 22:25:03
5. View Comment

I got the sample and the test working. Thanks a lot. Here's web.xml for the sample:

&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;

&lt;web-app id=&quot;WebApp_9&quot; version=&quot;2.4&quot; xmlns=&quot;<a href="http://java.sun.com/xml/ns/j2ee&quot;">http://java.sun.com/xml/ns/j2ee&quot;</a> xmlns:xsi=&quot;<a href="http://www.w3.org/2001/XMLSchema-instance&quot;">http://www.w3.org/2001/XMLSchema-instance&quot;</a> xsi:schemaLocation=&quot;<a href="http://java.sun.com/xml/ns/j2ee">http://java.sun.com/xml/ns/j2ee</a> <a href="http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd&quot;">http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd&quot;</a>&gt;

&#160;&#160;&#160; &lt;display-name&gt;Struts Blank&lt;/display-name&gt;

&#160;&#160;&#160; &lt;filter&gt;
&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;filter-name&gt;struts2&lt;/filter-name&gt;

&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;filter-class&gt;org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter&lt;/filter-class&gt;

&#160;&#160;&#160; &lt;/filter&gt;

&#160;&#160;&#160; &lt;filter-mapping&gt;
&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;filter-name&gt;struts2&lt;/filter-name&gt;

&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;url-pattern&gt;/*&lt;/url-pattern&gt;

&#160;&#160;&#160; &lt;/filter-mapping&gt;

&lt;/web-app&gt;

Also,
struts.xml --&gt;

&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;
&lt;!DOCTYPE struts PUBLIC

&#160;&#160;&#160; &quot;-//Apache Software Foundation//DTD Struts Configuration 2.0//EN&quot;

&#160;&#160;&#160; &quot;<a href="http://struts.apache.org/dtds/struts-2.0.dtd&quot;">http://struts.apache.org/dtds/struts-2.0.dtd&quot;</a>&gt;

&lt;struts&gt;

&#160;&#160;&#160; &lt;constant name=&quot;struts.enable.DynamicMethodInvocation&quot; value=&quot;false&quot; /&gt;
&#160;&#160;&#160; &lt;constant name=&quot;struts.devMode&quot; value=&quot;false&quot; /&gt;

&#160;&#160;&#160; &lt;!--
&#160;&#160;&#160; &lt;include file=&quot;example.xml&quot;/&gt;

&#160;&#160;&#160; &lt;package name=&quot;default&quot; namespace=&quot;/&quot; extends=&quot;struts-default&quot;&gt;
&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;default-action-ref name=&quot;index&quot; /&gt;

&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;action name=&quot;index&quot;&gt;

&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;result type=&quot;redirectAction&quot;&gt;

&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;param name=&quot;actionName&quot;&gt;HelloWorld&lt;/param&gt;

&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;param name=&quot;namespace&quot;&gt;/example&lt;/param&gt;

&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;/result&gt;

&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;/action&gt;

&#160;&#160;&#160; &lt;/package&gt;

--&gt;

&#160;&#160;&#160; &lt;!-- Add packages here --&gt;

&#160;&#160;&#160; &lt;package name=&quot;default&quot; namespace=&quot;/&quot; extends=&quot;struts-default&quot;&gt;

&#160;&#160;&#160;&#160;&#160; &lt;action name=&quot;HelloWorld&quot; class=&quot;com.thinkbeyond.action.HelloWorld&quot;&gt;

&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;result&gt;/HelloWorld.jsp&lt;/result&gt;

&#160;&#160;&#160;&#160;&#160; &lt;/action&gt;

&#160;&#160;&#160; &lt;/package&gt;

&lt;/struts&gt;


View Tutorial          By: Trishul at 2009-10-26 07:32:57
6. View Comment

thanks for this good example. i got error like (the requested resource (/Example1/index.jsp) is not available. here
Example1 is my own context i dont know what is the proplem what will i do pls reply


View Tutorial          By: anandhi at 2009-12-20 09:32:45
7. View Comment

please provide web.xml for this application.

View Tutorial          By: vandana at 2010-03-10 02:08:05
8. View Comment

/*Web.xml File */

&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;web-app version=&quot;2.4&quot;

&#160;&#160;&#160; xmlns=&quot;<a href="http://java.sun.com/xml/ns/j2ee&quot;">http://java.sun.com/xml/ns/j2ee&quot;</a>

&#160;&#160;&#160; xmlns:xsi=&quot;<a href="http://www.w3.org/2001/XMLSchema-instance&quot;">http://www.w3.org/2001/XMLSchema-instance&quot;</a>

&#160;&#160;&#160; xsi:schemaLocation=&quot;<a href="http://java.sun.com/xml/ns/j2ee">http://java.sun.com/xml/ns/j2ee</a>

<a href="http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd&quot;">http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd&quot;</a>&gt;

&#160;&#160;&#160; &lt;display-name&gt;Struts2 : Hello World&lt;/display-name&gt;

&#160;&#160;&#160; &lt;filter&gt;

&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;filter-name&gt;struts2&lt;/filter-name&gt;

&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;filter-class&gt;org.apache.struts2.dispatcher.FilterDispatcher&lt;/filter-class&gt;

&#160;&#160;&#160; &lt;/filter&gt;

&#160;&#160;&#160; &lt;filter-mapping&gt;

&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;filter-name&gt;struts2&lt;/filter-name&gt;

&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;url-pattern&gt;/*&lt;/url-pattern&gt;

&#160;&#160;&#160; &lt;/filter-mapping&gt;

&#160; &lt;welcome-file-list&gt;

&#160;&#160;&#160; &lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt;

&#160; &lt;/welcome-file-list&gt;

&lt;/web-app&gt;


View Tutorial          By: Pavan Barot at 2010-07-11 23:32:35
9. View Comment

Hi Sr,
I am doing u r program. I got error my project(Struts2Demo) is not available.Please give the solutions.
Note:
1)In web.xml, i can run html file with out filter tags.But with filter tags
error.
2)In html file I cant use the struts tags also, In-case i use, Its showing error.


View Tutorial          By: Dineshram P at 2011-09-06 14:11:00
10. View Comment

its nice example for beginers

View Tutorial          By: Ramesh at 2012-02-15 18:13:09
11. View Comment

sr
thanks 4 information provided
but i think web.xml add more value to this
thanks for urs knowledgeable information


View Tutorial          By: veer kumar at 2012-07-25 18:30:38

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Gokul Verma
Creating the first application using Struts 2
Editing struts-config.xml in a Struts Application
Editing web.xml in a Struts Application
The directories and files of a Struts application
Downloading and installing Struts

More Tutorials in Struts
Configuring JDBC DataSources in Struts
Struts Classes
FAQ: Why was reload removed from Struts (since 1.1)?
FAQ: Why are my checkboxes not being set from ON to OFF?
Using JavaScript to submit a form in Struts
How to prepopulate a form in Struts
Simple example of using the requiredif Validator rule in Struts
Chaining actions in Struts
When is the best time to validate input in Struts
What is a Plug-in and how to use Java plug-ins with Struts?
7 Best Practices of Struts
Origin and Architecture of Struts
ActionErrors and ActionError in Struts
Tutorial on Struts Configuration File - struts-config.xml in Struts - from the book: Struts Survival Guide. Basics to Best Practices
Handling multiple buttons in HTML Form in Struts

More Latest News
Most Viewed Articles (in Struts )
Tutorial on Struts Configuration File - struts-config.xml in Struts - from the book: Struts Survival Guide. Basics to Best Practices
Handling Duplicate Form Submissions in Struts
What is Struts? Which Version of Struts to use?
Struts 1 vs Struts 2
ActionErrors and ActionError in Struts
Using JavaScript to submit a form in Struts
MVC Architecture (Model 2 Architecture)
Introduction to Struts Architecture
Simple example of using the requiredif Validator rule in Struts
Editing struts-config.xml in a Struts Application
Struts and Tiles - Steps to use Struts and Tiles
Use ImageButtonBean for Image based Form Submits in Struts
Protecting JSPs from direct access in Struts
Chaining actions in Struts
What is a Model View Controller (MVC) Model?
Most Emailed Articles (in Struts)
What is Struts? Which Version of Struts to use?
Simple example of using the requiredif Validator rule in Struts
WebWork 2 is now Apache Struts 2
Using Multibox in Struts
Using Checkbox & Radio Tags, html:select, html:options in Struts Forms
Use ImageButtonBean for Image based Form Submits in Struts
Tutorial on Struts Configuration File - struts-config.xml in Struts - from the book: Struts Survival Guide. Basics to Best Practices
ForwardAction in Struts
IncludeAction in Struts
FAQ: Why was reload removed from Struts (since 1.1)?
Is Struts the most popular web application framework for Java?
Struts 1 vs Struts 2
Using Multiple Message Resource Bundles in Struts
What is a Model View Controller (MVC) Model?
Editing web.xml in a Struts Application