Struts2 Hello World

Struts 2 is a simple and extensible MVC framework for creating Java web application.

In this tutorial, we will create our first Struts 2 Hello World application.

 

1. Technologies used

  • Struts 2.3.16
  • Maven 3.0.5
  • Eclipse 4.2
  • JDK 1.6
  • Tomcat 6.0

 

2. Project structure

We create a Maven ‘s web application.

Struts2-Hello-World-1

 

3. Struts2 dependencies

To use Struts 2, we need to add struts2-core dependency in Maven’s pom.xml file as shown below.

 

4. Struts2 Action

It is a Java class that controls the interaction between the user, the model and the view.

It contains all business logic and it can, if necessary, access to other application layers.

Optionally, it can extend com.opensymphony.xwork2.ActionSupport or implement com.opensymphony.xwork2.Action.

In our example, execute method returns the success String to specify which view page will be rendered based on the mapping defined in struts.xml file.

 

5. JSP pages

File : index.jsp

When we click the submit button, the input value will be submitted to the WelcomeAction which is mapped to the welcome action in struts.xml

File : hello.jsp

This page is used to display the value returned by WelcomeAction class using s:property tag.

 

6. Struts2 Configuration

It contains the mappings to couple the action class (controller) and the jsp pages (view).

In our example, we will add two mappings :

  • the first one to tell which JSP page will be rendered  while the index action is requested
  • in the second one, we will map the welcome action to the WelcomeAction class, and we will tell which method of that class will be executed and what view to render il that method returns success value.

File : struts.xml

The namespace value is added to the URL after the application name.

 

7. Web app configuration

We add StrutsPrepareAndExecuteFilter filter to prepare and execute all phases of the Struts2 dispatching process.

File : web.xml

We used the url-pattern to tell which URLs will be served by StrutsPrepareAndExecuteFilter.

 

8. Test It

URL : http://localhost:8080/Struts2-Hello-World/Hello/index.action

Struts2-Hello-World-2

We enter a name and we click the submit button.

Struts2-Hello-World-3

 

Download source code