Login

Hello world struts2

Rodrigo

By Rodrigo

Created 2014-07-07 16:51:43 Modified 2014-07-07 21:51:50

Struts2 is a framework for web applications based in the mvc design pattern which is pretty useful when you need to build a web application, struts2 gives you all the tools that you need and the code is pretty clean and basing in the mvc architecture the code becomes even clearer

In this tutorial we are going to develop a basic hello world example using struts2 framework, eclipse tomcat and apache ant (the tool which build/compile the project), we are going to explain the code in detail in the Testing step, so don't worry about the code if you don't understand, until that point

this tutorial was written using the following gear:

  • Hardware:           laptop Thinkpad E430 Intel I5, 4gb Ram, 500gb HDD
  • OS:                    x86_64 GNU/Linux Ubuntu 14.10
  • Kernel:               3.13.0-29-generic
  • IDE/Text editor:   Eclipse Java EE IDE for Web Developers Version: Kepler Service Release 2
  • JDK:                   Java(TM) SE Runtime Environment (build 1.8.0_05-b13)
  • Struts:                struts-2.3.15.3
  • Tomcat:              apache-tomcat-6.0.35 (as a servlet container)
  • Browser:             Chromium Version 34.0.1847.116 Ubuntu 14.04 aura (260972)

 

1.- Setting up the environment:

First we need to add the necessary struts2 libraries to work on the example, so go to http://struts.apache.org/download.cgi and get the latest version then you need to add the following libraries to your project:

  • commons-fileupload-1.3.jar
  • commons-io-2.0.1.jar
  • commons-logging-1.1.3.jar
  • freemarker-2.3.19.jar
  • ognl-3.0.6.jar
  • struts2-core-2.3.15.3.jar
  • xwork-core-2.3.15.3.jar
  • javassist-3.11.0.GA.jar
  • commons-lang3-3.1.jar

this is my classpath:

<?xml version="1.0" encoding="UTF-8"?>
<classpath>
	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
	<classpathentry kind="var" path="TOMCAT_HOME/lib/servlet-api.jar"/>
	<classpathentry kind="var" path="TOMCAT_HOME/lib/jasper.jar"/>
	<classpathentry kind="var" path="TOMCAT_HOME/lib/jsp-api.jar"/>
	<classpathentry kind="var" path="TOMCAT_HOME/lib/el-api.jar"/>
	<classpathentry kind="var" path="TOMCAT_HOME/lib/annotations-api.jar"/>
	<classpathentry kind="src" path="WEB-INF/src"/>
	<classpathentry kind="src" output="work" path="work"/>
	<classpathentry kind="lib" path="WEB-INF/lib/commons-fileupload-1.3.jar"/>
	<classpathentry kind="lib" path="WEB-INF/lib/commons-io-2.0.1.jar"/>
	<classpathentry kind="lib" path="WEB-INF/lib/commons-logging-1.1.3.jar"/>
	<classpathentry kind="lib" path="WEB-INF/lib/freemarker-2.3.19.jar"/>
	<classpathentry kind="lib" path="WEB-INF/lib/ognl-3.0.6.jar"/>
	<classpathentry kind="lib" path="WEB-INF/lib/struts2-core-2.3.15.3.jar"/>
	<classpathentry kind="lib" path="WEB-INF/lib/xwork-core-2.3.15.3.jar"/>
	<classpathentry kind="lib" path="WEB-INF/lib/javassist-3.11.0.GA.jar"/>
	<classpathentry kind="lib" path="WEB-INF/lib/commons-lang3-3.1.jar"/>
	<classpathentry kind="output" path="WEB-INF/classes"/>
</classpath>

list directories:

2.- Creating the index page:

Once installed the libraries we can create our index page.
index.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!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">
<link rel="stylesheet" type="text/css" href="css/style.css">
<title>Hello World</title>
</head>
<body>
<s:form action="Hello">
	<s:textfield key="name"/>	
	<s:submit/>
</s:form>
</body>
</html>

3.- Creating the success page:

Now we have the index page which does a submit to the struts2 Hello action, if things goes well we should redirect to the success page and say hello, otherwise handle the error.
success.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!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">
<link rel="stylesheet" type="text/css" href="css/style.css">
<title>Hello World</title>
</head>
<body>
	<h3>Hello: <s:text name="name"/></h3>
</body>
</html>

4.- Creating the action class:

Up to this point we have created the 2 jsp, presentation pages, they have no logic inside, just the data presentation, so now we are going to create the struts2 action class which handles the requested data and validates them before to go success page

package com.rrivero.action;

import com.opensymphony.xwork2.ActionSupport;

public class HelloAction extends ActionSupport {

	private static final long serialVersionUID = 1L;
	private String name = "";

	public void validate() {
		if (name == null || name.equals(""))
			addFieldError("name", "Name not null");

		else if (name.length() < 4)
			addFieldError("name", "Name minimum length = 4");
	}

	@Override
	public String execute() throws Exception {

		return SUCCESS;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}

5.- Creating the struts.xml:

To work with struts2 we need to tell him what is the "Hello" mapping from the index.jsp when we click submit defined in the form->action tag

<?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>
	<package name="default" extends="struts-default">
				<action name="Hello" class="com.rrivero.action.HelloAction">	
					<result name="input">/index.jsp</result>	
					<result name="success">/WEB-INF/jsp/success.jsp</result>		
				</action>			
    </package>
    
</struts>

as you may see we are telling to the struts framework that the "Hello" mapping is going to go to the com.rrivero.HelloAction class

6.- Creating the web.xml:

Another thing we must do to work with struts is the "web" configuration, we did the application mapping configuration and now we need to tell to the application that we are using struts and the mappings will be handled by struts

<?xml version="1.0"?>
<!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>Hello World</display-name>
  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
  </filter>

  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

7.- Testing the app:

Up to this point we are done, now let's go to test how does struts2 work, go to http://127.0.0.1:8080/helloWorldStruts2/ you'll see the following page:

now let's click submit with empty name, we'll see the following page

Actions:

as you may see it says name not null, well, how did we get that? let me explain, in struts2 you have 5 main results

  • ERROR The action execution was a failure.
  • INPUT The action execution require more input in order to succeed.
  • LOGIN The action could not execute, since the user most was not logged in.
  • NONE The action execution was successful but do not show a view.
  • SUCCESS The action execution was successful.

and they can be also handled in the action as a method:

package com.rrivero.action;

import com.opensymphony.xwork2.ActionSupport;

public class HelloAction extends ActionSupport {
@Override public void validate() { if (name == null || name.equals("")) addFieldError("name", "Name not null"); else if (name.length() < 4) addFieldError("name", "Name minimum length = 4"); } @Override public String input() { //we prepare our form data, comboboxes etc... return INPUT; } @Override public String execute() throws Exception { //do all the logic AnotherClass anotherClass= new AnotherClass(); int inserts=anotherClass.insertData(); if(inserts>0) return SUCCESS; else return ERROR; } }

so validate method, validates the data before to use them, then if the data are correctly validated it continues with the execute method otherwise automatically it will return to the input again with the errors messages, input method; we can choose whether to handle the input or not, if you don't need to prepare the form with comboboxes or data from the database or any data that need to be processed before to go to the presentation page, you don't need to code the input method in the action, execute method is the one which execute the logic of the action, and the default method

Jsp:

Jsps in struts2 framework they only shows the data and/or gives a form to work on it, let's analyze the code, we have a different tag included to work with struts:

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

only then we can start to work with struts tags in our jsp there are a lot of tags to work with, let's see the form and submit:

<s:form action="Hello">
	<s:textfield key="name"/>	
	<s:submit/>
</s:form>

what we have here is a form tag saying that we are going to submit the data to the "Hello" mapping in the struts xml and also we are going to send a post variable which is called "name"

<action name="Hello" class="com.rrivero.action.HelloAction">	
					<result name="input">/index.jsp</result>	
					<result name="success">/WEB-INF/jsp/success.jsp</result>		
				</action>			

so, we have 2 results for the "Hello" mapping url, the input which goes to index, and success which goes to success page remember if we don't pass the validation we'll be redirected to input, so we need to tell struts where is "input"

Data:

To get the data in this case "name" post variable, and even if it was a get variable, we just need to create a private variable in our action called "name" with its getter and setter

package com.rrivero.action;

import com.opensymphony.xwork2.ActionSupport;

public class HelloAction extends ActionSupport {
	
	private static final long serialVersionUID = 1L;
	private String name="";
       /*... + methods...*/
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}	
}

now the data is stored, the "name" variable has a value, so we can use the "name" variable also in the next presentation page, in index we submit the "name" so we set the name via setName() (POST variable), and then we retrieve the "name" value, therefore we need to have the get method for this variable (getName()), we show the "name" variable in the next jsp

<h3>Hello: <s:text name="name"/></h3>

now type a name and submit the data

you'll see the following page

 

 

Download it in https://drive.google.com/file/d/0BwOqSob-RrBOamo3b2RZblh6VXc/edit?usp=sharing

8.- Conclusion:

Struts2 gives you very useful tools to work with web apps using the mvc design pattern, clear and elegant code, and it reduce your develop time considerably, the way how handles the data is very comfortable so you don't need to use servlets methods for get the requested data it doesn't matter if it is a get or post data sent you only need the getters and setters for the variable

9.- Reference links:




comments powered by Disqus