View RSS Feed

My Java Tips

Struts”Hello World”

Rate this Entry
by , 11-15-2011 at 07:15 PM (1520 Views)
Lets make a HelloWorld example using Struts.

Suppose you want to create a simple "Hello World" example that displays a welcome message. To create a "Hello World" example, you need to do three things:

1. Create a server page HelloWorld.jsp to present the messages

Java Code:
<%@ taglib prefix="s" uri="/struts-tags" %>
<h2><s:property value="message"></s:property></h2>
2. Create an Action class to create the message
Java Code:
package MyStrutsFolder;
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 {
        return SUCCESS;

    private String message;

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

    public String getMessage() {
        return message;
3. Create a mapping to couple the action and page

XML Code:
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
<package name=" MyStrutsFolder " extends="struts-default">
        <action name="HelloWorld" class=" MyStrutsFolder.HelloWorld">
        <!-- Add your actions here -->
Compile your Action to WEB-INF/classes and restart your container if necessary. Deploy the application and you should see a page with the title "Hello World!" and the message "Struts is up and running!".

Lets see how the code works.

Your browser sends to the web server a request for the URL.

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

I hope this helps.

Submit "Struts”Hello World”" to Facebook Submit "Struts”Hello World”" to Digg Submit "Struts”Hello World”" to Submit "Struts”Hello World”" to StumbleUpon Submit "Struts”Hello World”" to Google

Updated 11-15-2011 at 07:21 PM by Java Tip