Struts 2 Hello World Example

In my previous posts, I have written many examples and tutorials on JAX-RS RESTEasy, Spring 3, Hibernate and other java frameworks e.g. maven or junit. I got many requests to write something on struts 2 also. Well, Here I am starting with hello world example. In next posts, I will try to cover maximum areas and concepts involving struts 2. So, keep watching.

Sections in this post:
Create maven web project
Struts 2 dependencies
web.xml changes
Know struts.xml configuration file
Using struts.properties file
Writing first action class
Composing view files
Testing the application
Sourcecode download

Create maven web project

I will not eat much space here. You can read more details on how to create maven eclipse web project. In short, following commands are used.

mvn archetype:generate -DgroupId=com.howtodoinjava.struts2.example -DartifactId=struts2example -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

cd struts2example

mvn eclipse:eclipse -Dwtpversion=2.0

Struts 2 dependencies

I am using maven to import struts 2 runtime dependencies. It’s advantage is that you don’t need to remember and hunt for required dependencies manually and you get everything in one shot.

	<dependency>
		<groupId>org.apache.struts</groupId>
		<artifactId>struts2-core</artifactId>
		<version>2.3.15.1</version>
	</dependency>

If you want to see what all got included by this, look at below image: (Get the latest version jar files)

Struts 2 jar files
Struts 2 jar files

web.xml changes

Struts somehow needs to be plugged into your web application. It means that incoming requests to application should be handed over to struts for processing. This is done by adding a filter definition in web.xml file. This filter essentially redirect all incoming requests to StrutsPrepareAndExecuteFilter which then use configurations to handle that request.

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
  	<display-name>Archetype Created Web Application</display-name>
	
	<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>
	
</web-app>

Know struts.xml configuration file

So, StrutsPrepareAndExecuteFilter has got an request to handle. Now what? It will use the configuration to know how to handle a particular request. This configuration is defined in struts.xml file. This file will have url mappings specific to application workflow and their action handlers. It also defines the input/success/error views.

<?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>
	<include file="struts-default.xml"/>
	<package name="default" extends="struts-default">
	    <action name="">
            <result>/WEB-INF/jsp/index.jsp</result>
        </action>
	   <action name="testAction" class="com.howtodoinjava.struts2.example.web.TestAction">
	      <result name="input">/WEB-INF/jsp/index.jsp</result>
	      <result name="success">/WEB-INF/jsp/success.jsp</result>
	      <result name="error">/WEB-INF/jsp/index.jsp</result>
	   </action>
	</package>
</struts>

Using struts.properties file

Struts uses some default properties to configure its behavior on runtime. You can override these defaults in stuts.properties file.

#see http://struts.apache.org/2.0.14/docs/strutsproperties.html
struts.devMode=true
//message resource
struts.custom.i18n.resources=global

Writing first action class

This is important step because you will write the actual application logic here. Struts 2 actions usually extend ActionSupport class which provide some methods to override and change the application flow and inject your business logic in between.

package com.howtodoinjava.struts2.example.web;

import java.util.Date;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class TestAction extends ActionSupport 
{
	private String name;
    private Date nowDate;

    @Override
    public void validate(){
        if (name==null || name.length()==0)
            addActionError(getText("error.enter.message"));
    }

    @Override
    public String execute() throws Exception {
        nowDate = new Date();
        return ActionSupport.SUCCESS;
    }
    public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Date getNowDate() {
        return nowDate;
    }
}

Note: Struts 2 actions looks like POJO classes because they have to act as action forms also which were seperate entity in struts 1.

Composing view files

This is general step and involve writing view layer e.g. in our case we are writing jsp files. You can use the message resource to get messages from a property file which help in i18n later.

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <head>
        <title>Struts 2 hello world example</title>
        <s:head/>
    </head>

    <body>
        <h1><s:text name="welcome" /></h1>
        <s:if test="hasActionErrors()">
	        <div id="fieldErrors">
	            <s:actionerror/>
	        </div>
        </s:if>
        <s:form action="testAction" namespace="/" method="post" name="myForm" theme="xhtml">
            <s:textfield name="name" size="40" maxlength="40" key="your.message-label"/>
            <s:submit key="submit" />
        </s:form>
    </body>
</html>	

success.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <head>
        <title>Success Screen !!</title>
    </head>
    <body>
        <h2>Thank you for running this demo on <s:property value="nowDate" /></h2>
        <p>
            Your name recorded was: <h3><s:property value="name" /></h3>
        </p>
    </body>
</html>

The message resource file, they are using is:

global.properties

submit=Submit
your.message-label=Your Name
welcome=Welcome to Struts 2!
error.enter.message=Please enter your name !!

Testing the application

We are good to run our hello world application now. Lets hit the browser.

Type http://localhost:8080/struts2example/ and hit Enter

struts2-hello-world-1

Press Submit without entering anything

struts2-hello-world-2

Enter your name and press Submit

struts2-hello-world-3

That’s all friends for this struts 2 hello world application. If you want to download the source code of this tutorial, follow below given download link.


Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

8 thoughts on “Struts 2 Hello World Example”

  1. hi..As I’m confused with some maven commands so can you explain below things

    1.what is the reason of using mvn eclipse:eclipse from command line?
    2.what will happen when we run it from eclipse build target
    3.After we update the pom xml,it is really need to do as mvn eclipse:eclipse
    4.what is the role of Maven Update of eclipse mvn tool

    thanks.

    Reply
    • “mvn eclipse:eclipse” is used to generates the eclipse configuration files i.e .project and .classpath files. Without these files present, you will not be able to import project in eclipse.
      From build target, you will usually run “mvn clean install” i.e. project build specific commands; not eclipse related commands.

      “After we update the pom xml,it is really need to do as mvn eclipse:eclipse”?? Not necessarily. You can use commands like “mvn install” also. I also prefer to do it from eclipse using “Project -> Maven -> Update Configuration”.

      Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.