You are on page 1of 111

1

Struts

The framework documentation is written for active web developers and assumes a
working knowledge about how Java web applications are built. For more about the
underlying nuts and bolts, see the Key Technologies Primer.

Follow along with these tutorials to get started using Struts 2. The example code for the
tutorials available for checkout from the Struts 2 GitHub repository at struts-examples.
The example projects use Maven to manage the artifact dependencies and to build the
.war files.

The Struts 2 user mailing list is an excellent place to get help. If you are having a
problem getting the tutorial example applications to work search the Struts 2 mailing list.
If you don’t find an answer to your problem, post a question on the mailing list.

Examples
How to create a Struts 2 web application

Hello World Using Struts 2

Using Tags

Coding Actions

Processing Forms

Form Validation

Message Resource Files

Exception Handling

Debugging Struts

Form Tags

Form Validation Using XML

Control Tags

Wildcard Method Selection

Themes

Spring and Struts 2

Annotations

Navjot Singh – 9625544280 7827675929


2

Introducing Interceptors

Unit Testing

HTTP Session

Preparable Interface

Exclude Parameters

How To Create A Struts 2 Web Application

 Java Requirements
 Our First Application
 Create Struts 2 Web Application Using Maven To Manage Artifacts and To Build The
Application
 Step 1 - Create A Java Web Application
 to run the application using maven, add the jetty maven-plugin to your
pom.xml
 Step 2 - Add index.jsp
 Step 3 - Add Struts 2 Jar Files To Class Path
 Step 4 - Add Logging
 Step 5 - Add Struts 2 Servlet Filter
 Step 6 - Create struts.xml
 Step 7 - Build and Run the Application
 Getting Help

This tutorial walks through installing the framework and creating a simple application.

While the Struts 2 framework is simple to use, creating non-trivial applications assumes
a working knowledge of many J2EE technologies, including:

 Java
 Filters, JSP, and Tag Libraries
 JavaBeans
 HTML and HTTP
 Web Containers (such as Tomcat)
 XML
For more about supporting technologies, see the Key Technologies Primer.

Java Requirements
Struts 2 requires Servlet API 2.4 or higher, JSP 2.0 or higher, and Java 7 or higher.

Our First Application

Navjot Singh – 9625544280 7827675929


3

To get started using Struts 2 we will create a web application using Maven to manage
the artifact dependencies. You can checkout all the example applications from the
Struts 2 GitHub repository at struts-examples.

Create Struts 2 Web Application Using Maven To Manage


Artifacts and To Build The Application
This tutorial assumes you know how to create a Java web application that uses Maven
to manage artifacts and build the web application archive (war) file.

Step 1 - Create A Java Web Application

In your Java IDE create a Java web application with a project name
of basic_struts that follows the standard Maven project folder structure. In
your pom.xml include the following:

pom.xml build node

<build>
<finalName>basic-struts</finalName>
</build>

TO RUN THE APPLICATION USING MAVEN, ADD THE JETTY MAVEN-PLUGIN TO YOUR
POM.XML

pom.xml jetty plugin

<build>
...
<plugins>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.4.7.v20170914</version>
<configuration>
<webApp>
<contextPath>/${build.finalName}</contextPath>
</webApp>
<stopKey>CTRL+C</stopKey>
<stopPort>8999</stopPort>

Navjot Singh – 9625544280 7827675929


4

<scanIntervalSeconds>10</scanIntervalSeconds>
<scanTargets>
<scanTarget>src/main/webapp/WEB-INF/web.xml</scanTarget>
</scanTargets>
</configuration>
</plugin>
</plugins>
</build>

The above plugin will enable you to run the application using mvn jetty:run

Step 2 - Add index.jsp

Our next step is to add a simple index.jsp to this web application. Create
an index.jsp under src/main/webapp with a title of Basic Struts 2 Application -
Welcome and in the body add an h1 heading of Welcome To Struts 2!

index.jsp

<!DOCTYPE html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"
%>
<html>
<head>
<meta charset="UTF-8">
<title>Basic Struts 2 Application - Welcome</title>
</head>
<body>
<h1>Welcome To Struts 2!</h1>
</body>
</html>

Run mvn jetty:run to run the application.

In a web browser go to http://localhost:8080/basic-struts/index.jsp. You should see the


following:

Navjot Singh – 9625544280 7827675929


5

Step 3 - Add Struts 2 Jar Files To Class Path

Now that we know we have a working Java web application, let’s add the minimal
required Struts 2 framework Jar files to our web application’s class path. In pom.xml add
the following dependency node:

pom.xml dependency node

<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>${struts2.version}</version>
</dependency>

Of course replace the ${struts2.version} with the current Struts 2 version (or define
within pom properties). Maven will get the struts2-core jar and the other jar files
struts2-core requires (transitive dependencies).

Beginning with Struts version 2.2.3 you do not need to specify a separate dependency
node for javassist.

Step 4 - Add Logging

To see what’s happening under the hood, the example application for this tutorial uses
log4j2. Setup a log4j2.xml configuration in the src/main/resources folder which
contains the following

log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>


<Configuration>
<Appenders>
<Console name="STDOUT" target="SYSTEM_OUT">

Navjot Singh – 9625544280 7827675929


6

<PatternLayout pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>


</Console>
</Appenders>
<Loggers>
<Logger name="com.opensymphony.xwork2" level="debug"/>
<Logger name="org.apache.struts2" level="debug"/>
<Root level="warn">
<AppenderRef ref="STDOUT"/>
</Root>
</Loggers>
</Configuration>

Note the above log4j2 configuration specifies the console as the log target.

You’ll need to add a dependency node for log4j2 to the pom:

pom.xml log4j dependency node

<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j2.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j2.version}</version>
</dependency>

Using both log4j-core and log4j-api allows to use the latest version of Log4j2 without
a clash with version provided by the framework.

Optionally, if using maven bom ―bill of materials‖ in dependencyManagement section for


both Struts and log4j2, pom.xml will look like. Note that this way you can
omit version line for every used module, and all struts2-* and log4j-* modules are
managed to be of the same version. The struts2-bom is available since 2.3.20.

Navjot Singh – 9625544280 7827675929


7

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>

<struts2.version>2.5.14.1</struts2.version>
<log4j2.version>2.10.0</log4j2.version>
</properties>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-bom</artifactId>
<version>${struts2.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-bom</artifactId>
<version>${log4j2.version}</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>

<dependencies>
<!-- Struts 2 -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>

Navjot Singh – 9625544280 7827675929


8

</dependency>

<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
</dependency>
</dependencies>

Step 5 - Add Struts 2 Servlet Filter

To enable the Struts 2 framework to work with your web application you need to add a
Servlet filter class and filter mapping to web.xml. Below is how the web.xml may look
after adding the filter and filter-mapping nodes. web.xml is to be
under src/main/webapp/WEB-INF folder.

web.xml Servlet Filter

<?xml version="1.0" encoding="UTF-8"?>


<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/
ns/j2ee/web-app_2_4.xsd">
<display-name>Basic Struts2</display-name>
<welcome-file-list>
<welcome-file>index</welcome-file>
</welcome-file-list>

<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndE
xecuteFilter</filter-class>
</filter>

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

Navjot Singh – 9625544280 7827675929


9

</filter-mapping>

</web-app>

For more information about configuring the deployment descriptor for Struts 2 see Core
Developers Guide / web.xml page. Note the url-pattern node value is /* meaning the
Struts 2 filter will be applied to all URLs for this web application.

Step 6 - Create struts.xml

Struts 2 can use either an XML configuration file or annotations (or both) to specify the
relationship between a URL, a Java class, and a view page (such as index.jsp). For
our basic Struts 2 application, we’ll use a minimal xml configuration. Note the file name
is struts.xml and it should be in the src/main/resources folder (struts.xml must be
on the web application’s root class path).

struts.xml

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">

<struts>

<constant name="struts.devMode" value="true" />

<package name="basicstruts2" extends="struts-default">


<action name="index">
<result>/index.jsp</result>
</action>
</package>

</struts>

This minimal Struts 2 configuration file tells the framework that if the URL ends
in index.action to redirect the browser to index.jsp.

For more information about the struts.xml configuration file see struts.xml.

Navjot Singh – 9625544280 7827675929


10

Step 7 - Build and Run the Application

Run mvn jetty:run to run the web-application using the jetty maven-plugin.

View the console where you should see numerous debug messages that tell you the
Struts 2 framework is being included in the basic-struts2 web application.

Open a web browser and go to http://localhost:8080/basic-struts/index.action (note


that’s index.action not index.jsp at the end of the URL). You should see the same
web page as when going to http://localhost:8080/basic-struts/index.jsp. View the log
messages written to the console and you should find several that
discuss index.action and index.jsp:

Struts 2 Log Messages

...
2017-04-17 11:16:01,084 DEBUG [qtp1723848804-22] xwork2.DefaultActionProxy (DefaultAc
tionProxy.java:89) - Creating an DefaultActionProxy for namespace [/] and action name
[index]
...
2017-04-17 11:16:01,172 DEBUG [qtp1723848804-22] result.ServletDispatcherResult (Serv
letDispatcherResult.java:131) - Forwarding to location: /index.jsp
...

Getting Help
The Struts 2 user mailing list is an excellent place to get help. If you are having a
problem getting this Basic Struts 2 application to work search the Struts 2 mailing list. If
you don’t find an answer to your problem, post a question on the mailing list.

Navjot Singh – 9625544280 7827675929


11

Hello World Using Struts 2

 Description
 The Code
 Step 1 - Create The Model Class MessageStore.java
 Step 2 - Create The Action Class HelloWorldAction.java
 Step 3 - Create The View HelloWorld.jsp
 Step 4 - Add The Struts Configuration In struts.xml
 Step 5 - Create The URL Action
 Step 6 - Build the WAR File and Run The Application
 How the Code Works
 What to Remember

Description
When you click on a hyperlink or submit an HTML form in a Struts 2 web application,
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.

Suppose you want to create a simple ―Hello World‖ example that displays a welcome
message. After setting up an empty basic Struts 2 web application (see How To Create
A Struts 2 Web Application), to create a ―Hello World‖ example, you need to do four
things:

1. Create a class to store the welcome message (the model)


2. Create a server page to present the message (the view)
3. Create an Action class to control the interaction between the user, the model, and the
view (the controller)
4. Create a mapping (struts.xml) to couple the Action class and view

By creating these components, we are separating the work flow 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 model class, Action, server page, and mapping. If you like, fire
up your Java IDE, and enter the code as we go.

This tutorial assumes you’ve completed the How To Create A Struts 2 Web
Application tutorial and have a working basic Struts project. The example code for this
tutorial, helloworld, is available for checkout from the Struts 2 GitHub repository
at struts-examples. The example projects use Maven to manage the artifact
dependencies and to build the .war files.

The Code

Navjot Singh – 9625544280 7827675929


12

Let’s modify the basic-struts project to add the following:

 a model class to store our message


 a view that displays our message
 an Action class to act as the controller
 a configuration that ties everything together
The Struts 2 user mailing list is an excellent place to get help. If you are having a
problem getting this application to work search the Struts 2 mailing list. If you don’t find
an answer to your problem, post a question on the mailing list.

Step 1 - Create The Model Class MessageStore.java

Create the MessageStore class in src/main/java. Be sure to note the package


statement below.

Note that in the code shown below the JavaDoc comments are omitted. In the download
example, JavaDoc comments are included.

MessageStore.java

package org.apache.struts.helloworld.model;

public class MessageStore {


private String message;

public MessageStore() {
message = "Hello Struts User";
}

public String getMessage() {


return message;
}
}

Note the use of the public getter method to allow access to the private message String
attribute. The Struts 2 framework requires that objects you want to expose to the view
(HelloWorld.jsp) follow the JavaBean-style conventions.

Step 2 - Create The Action Class HelloWorldAction.java

We need an Action class to act as the Controller. The Action class responds to a user
action (in this example that action will be clicking an HTML hyperlink and sending a

Navjot Singh – 9625544280 7827675929


13

specific URL to the Servlet container). One or more of the Action class’s methods are
executed and a String result is returned. Based on the value of the result, a specific
view page (in this example that view page is HelloWorld.jsp) is rendered.

Note the package and import statements below.

HelloWorldAction.java

package org.apache.struts.helloworld.action;

import org.apache.struts.helloworld.model.MessageStore;

import com.opensymphony.xwork2.ActionSupport;

public class HelloWorldAction extends ActionSupport {


private MessageStore messageStore;

public String execute() {


messageStore = new MessageStore() ;

return SUCCESS;
}

public MessageStore getMessageStore() {


return messageStore;
}
}

The Struts 2 framework will create an object of the HelloWorldAction class and call the
execute method in response to a user’s action (clicking on a hyperlink that sends a
specific URL to the Servlet container).

In this example, the execute method creates an object of class MessageStore and then
returns the String constant SUCCESS.

Note also the public getter method for the private MessageStore object. Since we want
to make the MessageStore object available to the view page, HelloWorld.jsp, we need
to follow the JavaBean-style of providing getter and setter methods where needed.

Navjot Singh – 9625544280 7827675929


14

Step 3 - Create The View HelloWorld.jsp

We need a server page to present the message that is stored in the model
class MessageStore. Create the below JSP in the src/main/webapp folder.

HelloWorld.jsp

<!DOCTYPE html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"
%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello World!</title>
</head>
<body>
<h2><s:property value="messageStore.message" /></h2>
</body>
</html>

The taglib directive tells the Servlet container that this page will be using the Struts 2
tags and that these tags will be preceded by an s.

The <s:property> tag displays the value returned by calling the


method getMessageStore of the HelloWorldAction controller class. That method
returns a MessageStore object. By adding the .message onto the messageStore part of
the value attribute we are telling the Struts 2 framework to call the getMessage method
of that MessageStore object. The getMessage method of class MessageStore returns a
String. It is that String that will be displayed by the <s:property> tag.

We’ll learn more about tags in the next tutorial. See the Struts Tags for more information
about tags.

Step 4 - Add The Struts Configuration In struts.xml

We need a mapping to tie the URL, the HelloWorldAction class (controller), and
the HelloWorld.jsp (the view) together. The mapping tells the Struts 2 framework which
class will respond to the user’s action (the URL), which method of that class will be
executed, and what view to render based on the String result that method returns.

Navjot Singh – 9625544280 7827675929


15

Edit the struts.xml file (in the Mvn project that file is in the src/main/resources folder)
to add the action mapping. Place the action node (action name="hello") between the
opening and closing package node, just after the action mapping with the name="index".
Your complete struts.xml should look like:

struts.xml

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<constant name="struts.devMode" value="true" />

<package name="basicstruts2" extends="struts-default">


<action name="index">
<result>/index.jsp</result>
</action>

<action name="hello" class="org.apache.struts.helloworld.action.HelloWorldAct


ion" method="execute">
<result name="success">/HelloWorld.jsp</result>
</action>
</package>
</struts>

Step 5 - Create The URL Action

Let’s add an Action URL inside index.jsp (see src/main/webapp folder) so the user can
click on a link to tell the Struts 2 framework to run the execute method of
the HelloWorldAction class and render the HelloWorld.jsp view.

First add the taglib directive at the top of the jsp <%@ taglib prefix="s" uri="/struts-
tags" %>. Next add this p tag <p><a href="<s:url action='hello'/>">Hello
World</a></p> after the h1 tag. Your new index.jsp should look like:

index.jsp

<!DOCTYPE html>

Navjot Singh – 9625544280 7827675929


16

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"


%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Basic Struts 2 Application - Welcome</title>
</head>
<body>
<h1>Welcome To Struts 2!</h1>
<p><a href="<s:url action='hello'/>">Hello World</a></p>
</body>
</html>

The Struts url tag creates the URL with an action of hello. The hello action was mapped
to the HelloWorldAction class and its execute method. When the user clicks on the
above URL it will cause the Struts 2 framework to run the execute method of
the HelloWorldAction class. After that method returns the
String success (constant SUCCESS), the view page HelloWorld.jsp will be rendered.

Step 6 - Build the WAR File and Run The Application

Execute mvn jetty:run to run the application.

Go to this URL http://localhost:8080/helloworld/index.action where you should see the


following:

Click on the Hello World link and you should get the HelloWorld.jsp page:

Navjot Singh – 9625544280 7827675929


17

How the Code Works


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

1. The container receives from the web server a request for the resource hello.action.
According to the settings loaded from the web.xml, the container finds that all requests
are being routed
to org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter , including
the *.action requests. The StrutsPrepareAndExecuteFilter is the entry point into the
framework.
2. The framework looks for an action mapping named ―hello‖, and it finds that this mapping
corresponds to the class HelloWorldAction. The framework instantiates the Action and
calls the Action’s execute method.
3. The execute method creates the MessageStore object and
returns SUCCESS (="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="messageStore.message" /> tag calls the getter getMessageStore of
the HelloWorld Action and then calls the getMessage of the MessageStore object
returned by getMessageStore. The tag merges the value of the message attribute into
the response.
5. A pure HTML response is sent back to the browser.

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.

Navjot Singh – 9625544280 7827675929


18

Using Tags

 Struts 2 url Tag


 Struts 2 Form Tag
 Struts 2 property tag

This tutorial assumes you’ve completed the Hello World tutorial and have a
working helloworld project. The example code for this tutorial, using-tags, is available
for checkout from the Struts 2 GitHub repository at struts-examples. The example
projects use Maven to manage the artifact dependencies and to build the .war files.

In the Hello World lesson, we added a Struts 2 url tag to the index.jsp to create a
hyperlink to the hello.action. This tutorial will explore the url and other Struts 2 tags
further.

Web applications differ from conventional websites in that web applications can create a
dynamic response. To make it easier to reference dynamic data from a page, the Struts
2 framework offers a set of tags. Some of the tags mimic standard HTML tag while
providing added value. Other tags create non-standard, but useful controls.

To use the Struts 2 tags on the view page, you must include a tag library directive.
Typically, the taglib directive is <%@ taglib prefix="s" uri="/struts-tags" %>. So the
prefix for all the Struts 2 tags will be s. If you want to actually read the Struts 2 tag TLD
file, you’ll find it in the META-INF folder of the Struts 2 core jar.

Struts 2 url Tag


One use of the Struts 2 Tags is to create links to other web resources, especially to
other resources in the local application.

While HTML provides a simple a tag for creating hyperlinks, the HTML tag often
requires us to include redundant information. Also the HTML tag cannot easily access
dynamic data provided by the framework.

A very common use case in web applications is linking to other pages. In the Hello
World tutorial we added a link to hello.action inside the index.jsp using the Struts 2
url tag. Please refer to the url documentation for more information about the url tag.

index.jsp

<!DOCTYPE html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"
%>
<%@ taglib prefix="s" uri="/struts-tags" %>

<html>

Navjot Singh – 9625544280 7827675929


19

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Basic Struts 2 Application - Welcome</title>
</head>
<body>
<h1>Welcome To Struts 2!</h1>
<p><a href="<s:url action='hello'/>">Hello World</a></p>
</body>
</html>

When you run the Hello World tutorial in your Servlet container and then mouse over
the Hello World hyperlink created by the Struts 2 url tag you’ll see that the URL created
is hello.action (relative to the web context’s root folder).

Examine the struts.xml configuration in the Hello World tutorial and you will find this:

struts.xml

...
<action name="hello" class="org.apache.struts.helloworld.action.HelloWorldAction" met
hod="execute">
<result name="success">/HelloWorld.jsp</result>
</action>
...

The action node above maps the hello.action to the execute method of
class HelloWorldAction. If the execute method returns success, the view
page HelloWorld.jsp (in web context root folder) will be returned to the user.

A common use case is that the URL also needs to include a value for a query string
parameter such as userName. To add a query string parameter and its value use the
Struts 2 param tag, nested inside the url tag.

For the Using Tags tutorial add the following to index.jsp just after the link for Hello
World.

url tag with param

...

Navjot Singh – 9625544280 7827675929


20

<s:url action="hello" var="helloLink">


<s:param name="userName">Bruce Phillips</s:param>
</s:url>

<p><a href="${helloLink}">Hello Bruce Phillips</a></p>


...

Rather than put the url tag as the value for the anchor tag’s href attribute, we’ve
separated out the s:url tag into its own code block. Nested inside the url tag is the Struts
2 param tag. This tag lets you specify a parameter name ( e.g. userName) and a value
for that parameter (e.g. Bruce Phillips).

Notice the use of the var attribute. The value of the var attribute is a reference we can
use later in our code to refer to the url created.

Examine the anchor tag above. Notice the value of the href attribute is ${helloLink}.
The view page will substitute the hyperlink we created using the url tag for
the ${helloLink} reference. Note that the query string parameter will be properly URL-
encoded (Bruce+Phillips).

In the next tutorial we’ll cover how Struts can access the query string parameter value.

Struts 2 Form Tag


Most applications will use several data entry forms. The Struts 2 tags make creating
input forms easy. Consult the Form Tags Reference for all the details about the Struts 2
form tags.

Each of the Struts 2 form tags has numerous attributes to mimic the normal HTML form
tag attributes.

To create the outer shell of the form, use the Struts 2 form tag. The action attribute sets
the action name to submit to.

Add the following markup to index.jsp after the Hello Bruce Phillips link.

Struts 2 Form

<p>Get your own personal hello by filling out and submitting this form.</p>

<s:form action="hello">
<s:textfield name="userName" label="Your name" />

Navjot Singh – 9625544280 7827675929


21

<s:submit value="Submit" />


</s:form>

The Struts 2 textfield tag provides an input html tag of tag text and the submit tag
creates a submit button. When the index page is returned by the server to the browser
you should see:

The Struts form, textfield, and submit tags were converted to this HTML.

Struts Form Tags Converted To HTML

<form id="hello" name="hello" action="/using-tags/hello.action;jsessionid=6233ot11na1


mtshbr292hu1w" method="post">
<table class="wwFormTable">
<tr>
<td class="tdLabel"><label for="hello_userName" class="label">Your name:</label
></td>
<td class="tdInput"><input type="text" name="userName" value="" id="hello_userN
ame"/></td>
</tr>
<tr>

Navjot Singh – 9625544280 7827675929


22

<td colspan="2">
<div class="formButton">
<input type="submit" value="Submit" id="hello_0"/>
</div>
</td>
</tr>
</table>
</form>

Note how Struts 2 created a table inside the form to position the form elements. In later
tutorials you’ll learn how to specify the layout (table, CSS). The Struts 2 textfield tag
created an HTML input tag of type text with a name value that matches the name value
of the textfield tag. Struts 2 also created a label HTML tag based on the label value of
the textfield tag.

In the next tutorial we’ll cover how to use Struts 2 to process this form submission.

Struts 2 property tag


In the Hello World tutorial’s example application on JSP HelloWorld.jsp was this code:

Struts Property Tag

<s:property value="messageStore.message" />

The most common use of the property tag is to ―get‖ the value returned by calling a
public get method (of the Action class) and then to include that value in the HTML
returned to the browser.

As discussed in the Hello World tutorial, the value of messageStore.message instructs


Struts 2 to first call method getMessageStore of the Action class. That method call
returns a MessageStore object. The .message part instructs Struts 2 to call
the getMessage method of the MessageStore object. The getMessage method returns a
String which will be included in the HTML returned to the browser.

One very useful feature of the Struts 2 property tag is that it will automatically convert
the most common data types (int, double, boolean) to their String equivalents. To
demonstrate this feature let’s add a static int variable to class HelloWorldAction.

Add Static Field

private static int helloCount = 0;

Navjot Singh – 9625544280 7827675929


23

public int getHelloCount() {


return helloCount;
}

Each time the execute method is called we’ll increase helloCount by 1. So add this
code to the execute method of the HelloWorldAction class.

Increase helloCount

helloCount++;

Whenever a user clicks one of the links on the page index.jsp (or submits the form),
method execute of class HelloWorldAction will be run and the static
field helloCount will be increased by 1.

To include the value of the helloCount attribute in the HelloWorld.jsp we can use the
Struts 2 property tag. Add the following to HelloWorld.jsp after the h2 tag.

Use Property Tag To Display helloCount Value

<p>I've said hello <s:property value="helloCount" /> times!</p>

So even though the getHelloCount method returns an integer type, Struts 2 converted it
to type String and placed it into the body of the p tag.

Note that even though helloCount is a static field, the get method for helloCount is not
static. For Struts 2 to call the getHelloCount method to get the value of helloCount,
the getHelloCount method cannot be static.

If the value returned by the get method is an object, then the property tag will cause
Struts 2 to call the object’s toString method. Of course, you should always override
Class Object’s toString method in your model classes. Add the
following toString method to the MessageStore class:

Add toString Method To Class MessageStore

public String toString() {


return message + " (from toString)";
}

Add the following to HelloWorld.jsp

Navjot Singh – 9625544280 7827675929


24

Using Property Tag to Call toString

<p><s:property value="messageStore" /></p>

Since getMessageStore of HelloWorldAction class returns a MessageStore object,


Struts 2 will call the toString method of class MessageStore. The string returned by
that toString method will be displayed in the browser.

We covered a lot in this tutorial, but we’ve really only scratched the surface of how to
use the Struts 2 tags. Consult the Struts 2 Tag Reference for much more information
about all the Struts 2 tags.

Navjot Singh – 9625544280 7827675929


25

Coding actions

 Introduction
 Struts 2 Action Classes
 Processing Form Input In The Action Class
 Summary

This tutorial assumes you’ve completed the Using Struts 2 Tags tutorial and have a
working using-tags project. The example code for this tutorial, coding-actions, is
available for checkout from the Struts 2 GitHub repository struts-examples.

Introduction
Coding a Struts 2 Action involves several parts:

1. Mapping an action to a class


2. Mapping a result to a view
3. Writing the controller logic in the Action class

In the previous tutorials we covered how to configure Struts to map a URL such
as hello.action to an Action class such as HelloWorldAction (specifically the execute
method).

Action Mapping

<action name="hello" class="org.apache.struts.helloworld.action.HelloWorldAction" met


hod="execute">
<result name="success">/HelloWorld.jsp</result>
</action>

The Action mapping above also specified that if the execute method of
class HelloWorldAction returns success then the view HelloWorld.jsp will be returned
to the browser.

This tutorial will introduce you to the basics of writing the controller logic in the Action
class.

Struts 2 Action Classes


Action classes act as the controller in the MVC pattern. Action classes respond to a
user action, execute business logic (or call upon other classes to do that), and then
return a result that tells Struts what view to render.

Navjot Singh – 9625544280 7827675929


26

Struts 2 Action classes usually extend the ActionSupport class, which is provided by
the Struts 2 framework. Class ActionSupport provides default implementations for the
most common actions (e.g. execute, input) and also implements several useful Struts 2
interfaces. When your Action class extends class ActionSupport your class can either
override the default implementations or inherit them.

If you examine class HelloWorldAction from tutorial Using Struts 2 Tags you’ll see that it
extends the class ActionSupport and then overrides method execute.

The method execute is where we placed what we want this controller to do in response
to the hello.action.

Method execute of HelloWorldAction

public String execute() throws Exception {


messageStore = new MessageStore() ;

helloCount++;

return SUCCESS;
}

Note that method execute declares it throws an Exception. We’ll cover in a later tutorial
how to configure Struts to handle any Exceptions thrown from the Action classes
methods.

Processing Form Input In The Action Class


One of the most common responsibilities of the Action class is to process user input on
a form and then make the result of the processing available to the view page. To
illustrate this responsibility, let’s say that on our view page, HelloWorld.jsp, we want to
display a personal hello, such as ―Hello Struts User Bruce.‖

In the Using Struts 2 Tags example application we added a Struts 2 form to index.jsp.

Struts 2 Form Tags

<s:form action="hello">
<s:textfield name="userName" label="Your name" />

<s:submit value="Submit" />

</s:form>

Navjot Singh – 9625544280 7827675929


27

Make a note of the value of the name attribute for the Struts 2 textfield tag, which is
userName. When the user clicks on the submit button for the above form, the action
hello will be executed (hello.action). The form field values will be posted to the Struts
2 Action class (HelloWorldAction). The Action class may automatically receive those
form field values provided it has a public set method that matches the form field name
value.

So for the HelloWorldAction class to automatically receive the userName value it must
have a public method setUserName (note the JavaBean convention discussed in
tutorial Hello World).

For the example application associated with this tutorial, add the following Java code to
class HelloWorldAction.

Add userName to HelloWorldAction

private String userName;

public String getUserName() {


return userName;
}

public void setUserName(String userName) {


this.userName = userName;
}

To personalize the MessageStore message (recall that class MessageStore is storing


the message to display) add the following Java code to the HelloWorldAction’s execute
method after the statement that instantiates the MessageStore object.

Add userName value to message

if (userName != null) {
messageStore.setMessage( messageStore.getMessage() + " " + userName);
}

Now build and run (mvn jetty:run) the application. Enter your name in the form and
click the submit button. You should see the following page.

Navjot Singh – 9625544280 7827675929


28

When the form is submitted, Struts will call any set methods of the HelloWorldAction
class that match the form field names. So in this example method setUserName was
called and passed the value the user entered in the userName form field.

On the index.jsp we also have a Struts 2 action link (see tutorial Using Struts 2 Tags)
that includes a query string parameter: userName=Bruce+Phillips. If you click on that
link you should see the following result:

Since the query string parameter is userName, Struts passed the value of that parameter
to the setUserName method.

On the view page, HelloWorld.jsp, you can also access the userName value by using
the Struts 2 property tag (see tutorial Using Struts 2 Tags). Try showing just
the userName value on the view page.

Summary

Navjot Singh – 9625544280 7827675929


29

This tutorial introduced you to how to code the Action class so it can process user input
on a form or values in a query string parameter. If the form had numerous fields, it
would be cumbersome to have a set method that matches up with each form field. So
our next tutorial will cover how to integrate a model class, form fields in the view and
form processing in the Action class

Navjot Singh – 9625544280 7827675929


30

Processing Forms

 Introduction
 Forms and a Java model class
 Form structure
 Creating the Action class to handle the form submission
 Adding the view for the result
 Create action mapping in struts.xml
 Create a link to register.jsp

This tutorial assumes you’ve completed the Coding Struts 2 Actions tutorial and have a
working coding-actions project. The example code for this tutorial, form-processing,
is available for checkout from the Struts 2 GitHub repository struts-examples.

Introduction
In this tutorial we’ll explore using Struts 2 to do more involved processing of a form
submission. We’ll cover how to use a Java model class to store the form input and how
to create the Struts 2 form to match up with that model class.

The code provided in this tutorial may be added to the Coding Struts 2 Actions example
or you can download this complete example from the github respository -
https://github.com/apache/struts-examples.

The Struts 2 user mailing list is an excellent place to get help. If you are having a
problem getting the tutorial example applications to work search the Struts 2 mailing list.
If you don’t find an answer to your problem, post a question on the mailing list.

Forms and a Java model class


For this tutorial let’s say we need to provide a form that a user may submit to register for
a prize drawing. Our business rules state the user must provide his/her first name, last
name, email address, and age.

To encapsulate this data, we’ll use a simple Java class that follows the basic Java Bean
specifications (public set/get methods for each instance field). If you’re following along
add this class to the package org.apache.struts.register.model in the Coding Struts
2 Actions example.

Person.java

public class Person {


private String firstName;
private String lastName;

Navjot Singh – 9625544280 7827675929


31

private String email;


private int age;

public String getFirstName() {


return firstName;
}

public void setFirstName(String firstName) {


this.firstName = firstName;
}

public String getLastName() {


return lastName;
}

public void setLastName(String lastName) {


this.lastName = lastName;
}

public String getEmail() {


return email;
}

public void setEmail(String email) {


this.email = email;
}

public int getAge() {


return age;
}

public void setAge(int age) {


this.age = age;

Navjot Singh – 9625544280 7827675929


32

public String toString() {


return "First Name: " + getFirstName() + " Last Name: " + getLastName() +
" Email: " + getEmail() + " Age: " + getAge() ;
}
}

Note a few points about the above class. There is a public set/get method for each
instance field. The age attribute is of type integer. We’ve defined a
public toString method that returns a String representing the state of the object. Since
we haven’t specified a constructor, Java will provide a default constructor that will set all
instance fields to their null values.

Form structure
To collect the above information we’ll use a Struts 2 form. When creating this form the
key concept we need to employ is to tie each form field to a specific instance field of an
object of type Person. Let’s look over the form first and then discuss some key points.
Create a view page named register.jsp (in src/main/webapp)

register.jsp

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


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%
>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Register</title>
</head>
<body>
<h3>Register for a prize by completing this form.</h3>

<s:form action="register">
<s:textfield name="personBean.firstName" label="First name" />

Navjot Singh – 9625544280 7827675929


33

<s:textfield name="personBean.lastName" label="Last name" />


<s:textfield name="personBean.email" label ="Email"/>
<s:textfield name="personBean.age" label="Age" />
<s:submit/>
</s:form>
</body>
</html>

Since we are using Struts 2 tags, at the top of the page we need the Struts tag library
declaration.

The Struts 2 form will submit to an action named register. We’ll need to define that
action in our struts.xml file.

Note the four Struts 2 textfield tags. Each tag has a name value that includes an
attribute of the Person class (e.g. firstName). The name attribute’s value also has a
reference to an object called personBean. This object is of type Person. When we create
the Action class that handles this form submission, we’ll have to specify that object in
that Action class (see below).

The complete name value, personBean.firstName, instructs Struts 2 to use the input
value for that textfield as the argument to the personBean
object’s setFirstName method. So if the user types ―Bruce‖ in the textfield that has the
label ―First name‖, the personBean’s firstName instance field will have a value of
―Bruce‖.

Note that we have a Struts 2 textfield for each instance field of the class Person.
Remember that Person class’s age attribute is of type integer. All form field input values
are Strings. Struts 2 will automatically convert the String value (―25‖) the user entered
for the age form field to 25 when calling the setAge method of object personBean.

Creating the Action class to handle the form submission


When the user clicks on the submit button of the above form, the action ―register‖ and
the form data will be sent to the Struts 2 framework. We need an Action class to
process this form. If you recall from the tutorial Coding Struts 2 Actions our Action class
should extend the Struts 2 ActionSupport class.

Here is the Action class used for this example. Place it in package
org.apache.struts.register.action.

Register.java Struts 2 Action Class

Navjot Singh – 9625544280 7827675929


34

package org.apache.struts.register.action;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts.register.model.Person;

public class Register extends ActionSupport {

private static final long serialVersionUID = 1L;

private Person personBean;

public String execute() throws Exception {


//call Service class to store personBean's state in database

return SUCCESS;
}

public Person getPersonBean() {


return personBean;
}

public void setPersonBean(Person person) {


personBean = person;
}

In the Register class note that we’ve declared an attribute named personBean of
type Person and there is a public get and set method for this object.

The Register class also overrides the execute method. The execute method is the one
we will specify in the struts.xml to be called in response to the register action. In this
example, the execute method just returns the String constant SUCCESS (inherited from
the ActionSupport class). But in a real application, within the execute method we would

Navjot Singh – 9625544280 7827675929


35

call upon other classes (Service objects) to perform the business processing of the
form, such as storing the user’s input into a data repository.

The personBean object of type Person declared in the Register Action class matches
the personBean name we used in the form’s textfields. When the form is submitted, the
Struts 2 framework will inspect the Action class and look for an object
named personBean. It will create that object using the Person class’s default constructor.
Then for each form field that has a name value of personBean.someAttribute
(e.g personBean.firstName) it will call the personBean’s public set method for that
attribute and pass it the form field’s value (the user input). This all happens before the
execute method occurs.

When Struts 2 runs the execute method of class Register, the personBean object in
class Register now has values for its instance fields that are equal to the values the
user entered into the corresponding form fields.

By using a Java model class to encapsulate the data provided by the form we don’t
have to have a separate attribute (with public set/get methods) in the Action class
(Register) for each form field.

Adding the view for the result


When SUCCESS is returned by the execute method we want to display a simple thank you
page that shows the user’s registration. Add the thankyou.jsp below
to src/main/webapp.

thankyou.jsp

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


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%
>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Registration Successful</title>
</head>
<body>
<h3>Thank you for registering for a prize.</h3>

<p>Your registration information: <s:property value="personBean" /> </p>

Navjot Singh – 9625544280 7827675929


36

<p><a href="<s:url action='index' />" >Return to home page</a>.</p>


</body>
</html>

If you don’t recall how the Struts 2 property and url tags work consult the Using Struts 2
Tags tutorial.

Create action mapping in struts.xml


To specify the relationship between the form submission page, the Struts 2 Action class,
and the success view page we need to add an action node to struts.xml. Add this
action node to struts.xml (src/main/resources) after the hello action and before the
closing package node.

action node for struts.xml

<action name="register" class="org.apache.struts.register.action.Register" method="ex


ecute">
<result name="success">/thankyou.jsp</result>
</action>

The above action tells Struts 2 that when the register action is provided to call
method execute of class Register. If that method returns result ―success‖ return to the
browser the thankyou.jsp.

Note that we don’t need to tell Struts 2 anything about processing the form. The transfer
of the form field input values to the personBean object will happen automatically
provided we’ve followed the convention of naming our form fields to match
personBean.attributeName (e.g. personBean.lastName).

Create a link to register.jsp


So that the user can find the registration page, add this link to index.jsp

Link to register.jsp

<p><a href="register.jsp">Please register</a> for our prize drawing.</p>

Run The Example

If everything is correct, you should be able to run the application (using mvn jetty:run),
and open this URL in your web browser: http://localhost:8080/form-

Navjot Singh – 9625544280 7827675929


37

processing/index.action. On that page should be a link to register. Click on that link and
you should see the register.jsp page.

Fill out the form and click the submit button. You should then see
the thankyou.jsp page.

Navjot Singh – 9625544280 7827675929


38

Form Validation

 Introduction
 Add validate Method
 Handle Input Being Returned
 Error Messages
 Styling The Error Messages
 Summary
 Up Next

This tutorial assumes you’ve completed the Processing Forms tutorial and have a
working form-processing project. The example code for this tutorial, form-validation,
is available for checkout from the Struts 2 GitHub repository struts-examples.

Introduction
In this tutorial we’ll explore using Struts 2 to validate the user’s input on a form. There
are two ways you can use Struts 2 to do form validation. This tutorial will cover the more
basic method, where the validation is included in the Struts 2 Action class.

The Struts 2 user mailing list is an excellent place to get help. If you are having a
problem getting the tutorial example applications to work search the Struts 2 mailing list.
If you don’t find an answer to your problem, post a question on the mailing list.

Add validate Method


To enable the Struts 2 Action class to validate a user’s input on a Struts 2 form, you
must define a validate method in your Action class. Using the example from Processing
Forms tutorial, let’s say that we have these business rules:

1. User must provide a first name


2. User must provide an email address
3. User younger than 18 cannot register

If you recall from the Processing Forms tutorial the user’s input into the form fields is
placed by Struts 2 into the Java model class personBean. So a user’s input into
the firstName field would end up as the value for personBean’s firstName instance field
(via the personBean.setFirstName method).

In the validate method we can refer to get the values of personBean’s instance fields by
using the appropriate get methods. Once we have the values we can employ logic to
enforce our business rules.

Add the following validate method to Register.java (the Action class).

Navjot Singh – 9625544280 7827675929


39

validate method

public void validate(){


if (personBean.getFirstName().length() == 0) {
addFieldError("personBean.firstName", "First name is required.");
}

if (personBean.getEmail().length() == 0) {
addFieldError("personBean.email", "Email is required.");
}

if (personBean.getAge() < 18) {


addFieldError("personBean.age", "Age is required and must be 18 or older");
}
}

When the user presses the submit button on the register form, Struts 2 will transfer the
user’s input to the personBean’s instance fields. Then Struts 2 will automatically
execute the validate method. If any of the if statements are true, Struts 2 will call
its addFieldError method (which our Action class inherited by extending
ActionSupport).

If any errors have been added then Struts 2 will not proceed to call the execute method.
Rather the Struts 2 framework will return input as the result of calling the action.

Handle Input Being Returned


So what should we do if Struts 2 returns input indicating that the user’s input in the form
is not valid? In most cases we will want to redisplay the web page that has the form and
include in the form error messages to inform the user what is wrong.

To handle the return value of input we need to add the following result to our action
node in struts.xml.

<result name="input">/register.jsp</result>

The above result node goes just after the success result node for the register action and
before the closing of the action node.

Error Messages
Navjot Singh – 9625544280 7827675929
40

So when validation fails and Struts 2 returns input, the Struts 2 framework will redisplay
the register.jsp. Since we used Struts 2 form tags, automatically Struts 2 will add the
error messages. These error messages are the ones we specified in
the addFieldError method call. The addFieldError method takes two arguments. The
first is the form field name to which the error applies and the second is the error
message to display above that form field.

So the following addFieldError method call:

addFieldError("personBean.firstName", "First name is required.")

will cause the message First name is required to be displayed above the firstName field
on the form.

If you have made the above changes to the Processing Forms tutorial or you have
downloaded from form-validation run the application (see the README.txt in the project
root folder). Click on the Please register link. On the registration form, just click the
submit button and you should see:

Struts 2 called the validate method, validation failed, the register.jsp was displayed
with the error messages.

Styling The Error Messages


The Struts 2 s:head tag can be used to provide CSS that includes a style for the error
message. Add <s:head /> to register.jsp before the closing HTML </head> tag. Go
through the same steps as above and you should see:

Navjot Singh – 9625544280 7827675929


41

Summary
This tutorial covered validating a user’s form input by adding a validate method to an
Action class. There is another more sophisticated way to validate user input using XML.
If you want to learn more about using XML for validation in Struts 2 see Validation

Navjot Singh – 9625544280 7827675929


42

Message Resource Files

 Introduction
 Message Resource Property Files
 Struts 2 Key Attribute
 Struts 2 Text Tag
 Package Level Properties
 Global Properties
 Internationalization (i18n)
 Summary

This tutorial assumes you’ve completed the Form Validation tutorial and have a
working form-validation project. The example code for this tutorial, message-
resource, is available for checkout from the Struts 2 GitHub repository at struts-
examples.

Introduction
In this tutorial we’ll explore using Struts 2 message resource capabilities (also called
resource bundles). Message resources provide a simple way to put text in a view page
that is the same throughout your application, to create form field labels, and to change
text to a specific language based on the user’s locale (i18n).

The Struts 2 user mailing list is an excellent place to get help. If you are having a
problem getting the tutorial example applications to work search the Struts 2 mailing list.
If you don’t find an answer to your problem, post a question on the mailing list.

Message Resource Property Files


In a Struts 2 web application you may associate a message resource property file with
each Struts 2 Action class by creating a properties file with the same name as the
Action class and having the .properties extension. This properties file must go in the
same package as the Action class. For our tutorial example, let’s say we want to place
the form field labels into a separate file where we can easily change them and also
provide the capability to display the labels in other languages.

If you’re doing this tutorial after completing Form Validation then you can make these
changes to that tutorial’s example application.

Put the text below in a file named Register.properties in


the org.apache.struts.register.action package in the src/main/resources folder.

Register.properties

personBean.firstName=First name
personBean.lastName=Last name

Navjot Singh – 9625544280 7827675929


43

personBean.age=Age
personBean.email=Email
thankyou=Thank you for registering %{personBean.firstName}.

The above is just a standard Java properties file. The key is to the left of the = sign and
the value for the key is to the right. When the Register action is executed these
properties will be available to the view page by referencing the key name.

Struts 2 Key Attribute


The Struts 2 key attribute can be used in the textfield tag to instruct the framework what
value to use for the textfield’s name and label attributes. Instead of providing those
attributes and their values directly, you can just use the key attribute.

If you open register.jsp from the Form Validation tutorial you’ll see this Struts 2 textfield
tag:

textfield tag

<s:textfield name="personBean.firstName" label="First name" />

Instead of specifying the name and label attributes you can just use the key attribute.

textfield tag with key attribute

<s:textfield key="personBean.firstName" />

The value for the key attribute instructs the Struts 2 framework to use the same value
for the name attribute (personBean.firstName). For the label attribute’s value the value
of the key attribute is used by the Struts 2 framework to find a key in a properties file
with the same value. So in our example, Struts 2 will look in Register.properties for a
key with a value of personBean.firstName. The value of that key (First name) will be
used as the label attribute’s value.

To enable the key attribute to find the properties file, the display of the view page must
be the result of executing a Struts 2 Action class. Right now if you examine index.jsp
from the Form Validation tutorial the link to the register.jsp page is a standard URL.

link to register.jsp

<p><a href="register.jsp">Please register</a> for our prize drawing.</p>

Navjot Singh – 9625544280 7827675929


44

We need to change the above link so that it goes through the Register.java Struts 2
Action class. Replace the above with this markup.

link to Register Action class

<s:url action="registerInput" var="registerInputLink" />


<p><s:a href="%{registerInputLink}">Please register</s:a> for our prize drawing.</p>

We use the Struts 2 url tag to create a link to action registerInput. We then use that link
as the value for the href attribute of the anchor tag. We must define the registerInput
action in struts.xml. Add the following to struts.xml

registerInput action node for struts.xml

<action name="registerInput" class="org.apache.struts.register.action.Register" metho


d="input" >
<result name="input">/register.jsp</result>
</action>

The above action node instructs the Struts 2 framework to execute class Register’s
input method in response to action registerInput. The input method is inherited by
class Register from class ActionSupport. The default behavior of the inherited input
method is to return the String input. The result node above specifies that if the returned
result is input then render the view register.jsp.

By doing the above the view page register.jsp will have access to the properties
defined in Register.properties. The Struts 2 framework will make those properties
defined in Register.properties available to the view page since the view page was
rendered after Register.java (the Struts 2 Action class) was executed.

Follow the instructions (README.txt) in the project to create the war file and copy the
war file to your servlet container. Open a web browser and navigate to the home page
specified in the README.txt file (index.action). You should see a link
to registerInput.action when mousing over the hyperlink Please Register.

Navjot Singh – 9625544280 7827675929


45

When you click on the Please Register link your browser should display
the register.jsp. The form field labels should be the key values from
the Register.properties file.

Struts 2 Text Tag


We can also use the Struts 2 text tag to display values from a properties file.
In thankyou.jsp add this text tag instead of the h3 tag that is in thankyou.jsp.

text tag

Navjot Singh – 9625544280 7827675929


46

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

Since thankyou.jsp is also rendered after executing the Register.java Action class,
the key thankyou and its value will be available to the view page.

How did the value entered for the first name input field get displayed on thankyou.jsp?
Look back at the value for the thankyou key in the Register.properties file.

Register.properties

thankyou=Thank you for registering %{personBean.firstName}.

The markup %{personBean.firstName} tells Struts 2 to replace this part with the result
of calling getPersonBean, which returns a Person object. Then call
the getFirstName method which returns a String (the value the user inputted into
the personBean.firstName form field on register.jsp).

Package Level Properties


What if you want a properties file with keys and values that can be referenced from
multiple view pages and those view pages are rendered after executing different Action
classes? Struts 2 has the ability to use multiple property files provided the property file
is found in the package hierarchy.

Place the following in a file named package.properties and save that file in
package org.apache.struts in src/main/resources.

package.properties

greeting=Welcome to The Wonderful World of Struts 2

Now any view rendered by an Action that is in the hierarchy org.apache.struts... can
use a Struts 2 text tag with a name attribute value of greeting to display the value of

Navjot Singh – 9625544280 7827675929


47

the greeting property key. For example add the following markup
to helloworld.jsp before the h2 tag.

Using properties set in package.properties

<h1><s:text name="greeting" /></h1>

Then rebuild the war file and deploy it to your servlet container. Go to index.action and
click on the link for Hello World. You should see:

The property keys and values defined in package.properties are available to any view
that is rendered after executing an Action class that is the package hierarchy that
includes package.properties.

Global Properties
You can also specify a global property file in struts.xml. The keys and values defined
in that property file will be available to all the view pages that are rendered after
executing an Action class.

Add the following to a file named global.properties (note the name doesn’t have to be
global).

global.properties

contact=For assistance contact <a href='mailto:contact@email.com'>contact@email.com</


a>

Save the global.properties file in the src/main/resources folder.

Navjot Singh – 9625544280 7827675929


48

To inform the Struts 2 framework about the global.properties file add the follow node
to struts.xml after the constant name="struts.devmode" node.

Specify Global Property File In struts.xml

<constant name="struts.custom.i18n.resources" value="global" />

To use the contact key in a view page, add the following markup to index.jsp just
before the closing body tag.

Using contact property

<hr />
<s:text name="contact" />

Rebuild the war file, deploy it to your Servlet container, and then go to index.action.
You should see:

Struts 2 will look for a property key of contact in all the property files starting with the
property file that matches the Action class, then in the property files that are in the
package hierarchy of the Action class, and then in any property files specified
in struts.xml. For this example Struts 2 will find the contact key in global.properties.
The value of the contact key will be displayed where we have put the text tag.

Navjot Singh – 9625544280 7827675929


49

You can add the text tag above to all the JSPs in this example.

Internationalization (i18n)
Using message resource files (resource bundles) also enables you to provide text in
different languages. By default, Struts 2 will use the user’s default locale. If that locale is
en for English then the property files used will be the ones without a locale specification
(for example Register.properties). If the locale is not English but say Spanish (es)
then Struts 2 will look for a properties file named Register_es.properties.

To provide an example of Struts 2 support for i18n create a file


named Register_es.properties and in that file add the following Spanish translations.

Register_es.properties

personBean.firstName=Nombre
personBean.lastName=Apellidos
personBean.age=Edad
personBean.email=Correo
thankyou=Gracias por registrarse, %{personBean.firstName}.

My apologies to Spanish language speakers for any mistakes in the Spanish


translations.

Save the Register_es.properties file in the same package as Register.properties.

In our example application, we need to tell Struts 2 to use a locale value of es (since
we’re not in a Spanish locale) instead of the default locale value of our location (which is
en). Add the following markup to index.jsp.

Specify The Locale As a URL Parameter

<h3>Registro español</h3>
<s:url action="registerInput" var="registerInputLinkES">
<s:param name="request_locale">es</s:param>
</s:url>

<p><s:a href="%{registerInputLinkES}">Por favor, regístrese</s:a> para nuestro sorteo


</p>

In the above markup we’ve added a parameter named request_locale to the URL. The
value of that parameter is es. The Action class that responds to this URL
(Register.java) will see that the locale is es and will look for property files with _es (for
Navjot Singh – 9625544280 7827675929
50

example Register_es.properties). It will use those property files to find the values of
the property keys referenced by the view page (e.g. personBean.firstName).

After clicking on the above link you should see the same form as before but with the
form field labels in Spanish.

If we implement the same concept by creating _es.properties versions


of global.properties (global_es.properties)
and package.properties (package_es.properties) then we can create a complete
registration web page in Spanish. Download the finished example application for this
tutorial from Github - message-resource to see those property files and run the
complete example with the registration form in Spanish.

Summary
We’ve covered how to use message resources (resource bundles) in Struts 2 and also
introduced how Struts 2 enables internationalization (i18n) in this tutorial. To fully
understand these concepts and learn more about Struts 2 consult the main Struts 2
documentation available at http://struts.apache.org.

Navjot Singh – 9625544280 7827675929


51

Exception Handling

 Introduction
 Global Exception Handling
 Exception Handling Per Action
 Logging Exceptions
 Display Exception Information In Browser
 Summary

The code for this tutorial, exception-handling, is available for checkout at struts-
examples.

Introduction
In this tutorial we’ll explore how to enable the Struts 2 framework to handle any
uncaught exceptions generated by a web application. Struts 2 provides robust exception
handling, including the ability to automatically log any uncaught exceptions and redirect
the user to an error web page.

The Struts 2 user mailing list is an excellent place to get help. If you are having a
problem getting the tutorial example applications to work search the Struts 2 mailing list.
If you don’t find an answer to your problem, post a question on the mailing list.

Global Exception Handling


Using the Struts 2 framework you can specify in the struts.xml how the framework
should handle uncaught exceptions. The handling logic can apply to all actions (global
exception handling) or to a specific action. Let’s first discuss how to enable global
exception handling.

To enable global exception handling you need to add two nodes to struts.xml: global-
exception-mapping and global-results. For example examine the struts.xml from the
exception-handling project.

<global-results>
<result name="securityerror">/securityerror.jsp</result>
<result name="error">/error.jsp</result>
</global-results>

<global-exception-mappings>

<exception-mapping exception="org.apache.struts.register.exceptions.SecurityBreac
hException" result="securityerror" />
<exception-mapping exception="java.lang.Exception" result="error" />

Navjot Singh – 9625544280 7827675929


52

</global-exception-mappings>

The global exception mapping node tells the Struts 2 framework what to do if an
uncaught exception of the type specified (or a child of that type) is thrown by the the
application. For example if a SecurityBreachException is thrown but not caught, the
Struts 2 Action class will return a result of ―securityerror‖. All other uncaught exceptions
will cause the Struts 2 Action class to return a result of ―error‖.

The global results mapping node relates the result value to a specific view page. For
example the result ―securityerror‖ will cause the framework to redirect the user’s
browser to the securityerror.jsp view page.

Exception Handling Per Action


If you need to handle an exception in a specific way for a certain action you can use the
exception-mapping node within the action node.

<action name="actionspecificexception" class="org.apache.struts.register.action.Regis


ter" method="throwSecurityException">
<exception-mapping exception="org.apache.struts.register.exceptions.SecurityBreach
Exception" result="login" />
<result>/register.jsp</result>
<result name="login">/login.jsp</result>
</action>

The above action node from the example application’s struts.xml file specifies that if the
method throwSecurityException throws an uncaught exception of
type SecurityBreachException the Struts 2 framework should return a result of login.
The login result will cause the user’s browser to be redirected to login.jsp.

You can see that an action-specific exception mapping will take precedence if the same
exception is also mapped globally.

Logging Exceptions
You can configure the Struts 2 framework to log any uncaught exceptions. To enable
logging of the exceptions being handled by the Struts 2 framework you must specify
some parameter values in struts.xml. If you examine the ExceptionMappingInterceptor
class API there are three parameter values you can set to enable logging (logEnabled),
the log level to use (logLevel), and the log category (logCategory) to specify in the log
message.

To set these parameter values for all actions that use a specific stack of interceptors in
a package include the following in struts.xml just after the opening package node.
Navjot Singh – 9625544280 7827675929
53

<interceptors>
<interceptor-stack name="appDefaultStack">
<interceptor-ref name="defaultStack">
<param name="exception.logEnabled">true</param>
<param name="exception.logLevel">ERROR</param>
</interceptor-ref>
</interceptor-stack>
</interceptors>

<default-interceptor-ref name="appDefaultStack" />

The above interceptors node configures a new stack of Struts 2 interceptors


named appDefaultStack. This stack of interceptors is based upon the defaultStack of
interceptors (which are the Struts 2 interceptors that execute by default whenever an
Action class method is called by the Struts 2 framework).

The ExceptionMappingInterceptor is one of the Struts 2 interceptors that is part of the


default stack. In the definition of the struts defaultStack, the
ExceptionMappingInterceptor is given the name of exception. By specifying a param
node with the name of exception.logEnabled and a value of true, I’m setting the
logEnabled parameter of the ExceptionMappingInterceptor class to true.

Now when the application throws an uncaught exception, the Struts 2 framework will
handle it and will also write an entry to the log that includes the stack trace. In the
example above, I’ve set the level to log these exceptions to be ERROR.

In the example applications, the logging is just to the Servlet container’s console (see
the log4j2.xml file for the log settings).

Display Exception Information In Browser


You can display information about the exception in the browser if you want by using
s:property tags with a value of exception and exceptionStack. For example in error.jsp is
this markup.

<h4>The application has malfunctioned.</h4>

<p>Please contact technical support with the following information:</p>

<h4>Exception Name: <s:property value="exception" /> </h4>

Navjot Singh – 9625544280 7827675929


54

<h4>Exception Details: <s:property value="exceptionStack" /></h4>

When the exception interceptor is triggered it adds to the fields available for display the
exception message and the exception’s stack trace.

Summary
Struts 2 provides an easy to use configuration for handling uncaught exceptions and
redirecting users to appropriate view pages. You can configure exception handling to be
global for all actions or to just for a specific action. You can also enable the Struts 2
framework to log the uncaught exceptions.

Navjot Singh – 9625544280 7827675929


55

Debugging Struts

 Introduction
 Configuration Plugin
 Using the Debugging Interceptor
 Struts 2 Logging
 Summary

The example code for this tutorial, debugging-struts, is available for checkout at struts-
examples.

Introduction
During development of a Struts 2 web application you may want to view the information
being managed by the Struts 2 framework. This tutorial will cover two tools you can use
to see how Struts 2 views your web application. One tool is the Struts 2 configuration
plugin and the other is the debugging interceptor. This article also discusses how to set
the log level to see more or fewer log messages.

The Struts 2 user mailing list is an excellent place to get help. If you are having a
problem getting the tutorial example applications to work search the Struts 2 mailing list.
If you don’t find an answer to your problem, post a question on the mailing list.

Configuration Plugin
The Struts 2 config browser plugin provides details about the configuration the Struts 2
framework is using to run your application. To use the plugin your application needs to
have the struts2-config-browser-plugin-x.x.x.x.jar in your application’s class path. The
config-browser-plugin jar is part of the Struts 2 download and is also available in the
Maven repository.

To use the plugin in your application, just call index.action in namespace config-
browser. For example you could have the following link on your admin page (or just
anywhere during your development).

<a href='<s:url action="index" namespace="config-browser" />'>Launch the configuratio


n browser</a>

In the example application, there is a link to the configuration browser on the index.jsp
page.

Clicking on the link for the configuration browser will cause the Struts 2 framework to
return this page to your browser.

Navjot Singh – 9625544280 7827675929


56

You can click on an action link to see the configuration for that action. For example
clicking on the register action link results in this.

Navjot Singh – 9625544280 7827675929


57

You may then click on one of the tabs (Results, Exception Mappings, Interceptors,
Properties, Validators) to get more information about how the Struts 2 framework has
configured that specific action.

On the left side of the page is the config browser plugin menu. Clicking on constants will
render a view that lists all the Struts 2 constants and their properties for your
application. Clicking on beans shows the beans Struts 2 is managing. Clicking on Jars
shows the jars your application is using.

Using the Debugging Interceptor


If you have set devMode to true (in the example application see struts.xml) then one of
the interceptors that is activated when Struts 2 processes an action is the
DebuggingInterceptor. The DebuggingInterceptor looks for a query string appended to
the action URL with a name of debug and a value of xml, console, command, or
browser.

If the DebuggingInterceptor finds that query string then it will halt further execution of
the action and instead return to the browser debugging information. The format of the

Navjot Singh – 9625544280 7827675929


58

returned information depends on the value of the debug query parameter.


See DebuggingInterceptor for more detail.

In the example application on the index.jsp is a link for displaying debugging


information. This link includes the query string debug=browser. If you click on this link
you’ll see a table with columns that can be expanded and collapsed. The table contains
the various objects and their state being managed by the Struts 2 framework.

Note that to enable the correct display and interaction of the expand/collapse links on
the debugging information web page you need to include the s:head tag in your JSP’s
head section (see index.jsp in the example application) and also include the Struts 2
dojo plugin in your application’s class path. The Struts 2 dojo plugin is available as part
of the Struts 2 download and from the Maven repository.

Navjot Singh – 9625544280 7827675929


59

Struts 2 Logging
The Struts 2 framework will write to a log a great deal of information if you’ve configured
the log properties to log at the debug level. In the example application, view log4j2.xml.
The two major packages involved in the Struts 2
framework, com.opensymphony and org.apache.struts2, are configured to write debug
and above log messages. When you run the application view the standard out for your
Servlet container to see all the information written to the log. Please
check Logging page for other options.

Summary
Using the configuration browser plugin and the debugging interceptor can assist you in
trouble shooting a problem with a Struts 2 web application. These tools should only be
used in development.

Prior to creating your war file for deployment to production you should
change devMode to false and remove the debugging links. You may also want to adjust
the level of logging in your log properties file to a higher level (info or warn) to reduce
the number of log messages.

Navjot Singh – 9625544280 7827675929


60

Form Tags

 Introduction
 Example Application
 Struts 2 Select Tag
 Struts 2 Radio Tag
 Struts 2 Select Tag - Object Backed
 Struts 2 Checkbox Tag
 Struts 2 checkboxlist Tag
 Summary

The example code for this tutorial, form-tags, can be checked out from struts-
examples.

Introduction
In this tutorial we’ll explore some of the other Struts 2 form controls. In our previous
tutorials that explained how to use Struts 2 forms (Processing forms, Form validation,
and Message resource files ) we covered how to use the Struts 2 head, form, textfield
controls and the key attribute. This tutorial will explore using the Struts 2 select, radio,
checkbox, and checkboxlist form controls.

The Struts 2 user mailing list is an excellent place to get help. If you are having a
problem getting the tutorial example applications to work search the Struts 2 mailing list.
If you don’t find an answer to your problem, post a question on the mailing list.

Example Application
The example application that supports this tutorial shows how to use Struts 2 form tags
so that a user can edit his information. The information that can be edited is
encapsulated in an object of class Person. A Person object knows these things: first
name, last name, favorite sport, gender, state of residency, is or is not over 21, and car
models owned.

To enable the user to edit his information that is stored in the Person object, we need to
create a form like this one:

Navjot Singh – 9625544280 7827675929


61

The form allows the user to make changes. After submitting the form, the Struts 2
framework will update the state of the Person object.

The first and last names are shown on the form (see edit.jsp) using the Struts 2 textfield
tag, which we’ve discussed in previous tutorials.

Struts 2 Select Tag


A user can select one favorite sport from several choices. The example application uses
the Struts 2 select tag to provide the list of options for the select box.

Struts 2 Select Tag

<s:select key="personBean.sport" list="sports" />

In these form tags, we are using the key attribute as discussed in the Message resource
files tutorial. The key attribute is used by the Struts 2 framework to determine values for
the other attributes (e.g. label and value). We are also using a property file associated
with the EditAction class to provide the label values based on the key attribute value
(see the Message Resource Files tutorial for information on using Struts 2 property
files).

Note that there are many attributes for the Struts 2 form tags, most of which mirror the
HTML attributes associated with the tags. You can read about all the attributes for a
Struts 2 form tag by consulting the Struts 2 documentation.

Navjot Singh – 9625544280 7827675929


62

The value of the list attribute of the Struts 2 select tag is used by the framework to
determine what method of the action class to call in order to create the option values. In
our example application, the list attribute value of ―sports‖ results in the framework
calling the getSports method of class EditAction. That method returns a String array
containing ―football‖, ―baseball‖, and ―basketball‖. Those values are used to create the
option tags inside the select tag.

The Struts 2 framework determines which option is preselected by using the key
attribute’s value to call a method on the personBean object. Since the key attribute’s
value is ―personBean.sport‖, the framework calls the personBean object’s getSport
method. If the value returned by that method matches one of the option values, that
option will be marked as ―selected‖.

Here is the HTML that results from using the above Struts 2 select tag.

HTML Created By Struts 2 Select Tag

<tr>
<td class="tdLabel">
<label for="save_personBean_sport" class="label">Favorite sport:</label>
</td>
<td>
<select name="personBean.sport" id="save_personBean_sport">
<option value="football">football</option>
<option value="baseball">baseball</option>
<option value="basketball" selected="selected">basketball</option>
</select>
</td>
</tr>

Note the table formatting created by the Struts 2 framework when using the Struts 2
select tag. The CSS classes are defined in style sheets included by the Struts 2 s:head
tag. The Struts 2 s:head tag is placed inside the edit.jsp’s head section.

Since the personBean’s getSport method returns ―baskeball‖, the basketball option
value is marked as selected.

Struts 2 Radio Tag


The Struts 2 radio tag—like its standard HTML counterpart—is used to display 2 or
more choices, only one of which can be selected by the user. Here is the code for the
Struts 2 radio button from the example application.

Navjot Singh – 9625544280 7827675929


63

Struts 2 Radio Tag

<s:radio key="personBean.gender" list="genders" />

Again the key attribute’s value determines the value for the label and value attributes.
The label’s text is derived from the EditAction.properties file (key personBean.gender).
Just like the Struts 2 select tag, the list attribute of the Struts 2 radio tag causes the
framework to call the getGenders method of the EditAction class. The Array of String
objects returned are used to create the individual radio buttons.

HTML Created By Struts 2 Radio Tag

<tr>
<td class="tdLabel">
<label for="save_personBean_gender" class="label">Gender:</label>
</td>
<td>
<input type="radio" name="personBean.gender" id="save_personBean_gendermale"
value="male"/>
<label for="save_personBean_gendermale">male</label>

<input type="radio" name="personBean.gender" id="save_personBean_genderfemale


" value="female"/>
<label for="save_personBean_genderfemale">female</label>

<input type="radio" name="personBean.gender" id="save_personBean_gendernot su


re" checked="checked" value="not sure"/>
<label for="save_personBean_gendernot sure">not sure</label>
</td>
</tr>

Also just like the Struts 2 select tag the result returned by calling the personBean
object’s getGender method is used to determine which of the radio buttons is checked.

Struts 2 Select Tag - Object Backed


You may need to create a Struts 2 select tag where the options displayed to the user
each have their own value that is different from what is displayed. In the example
application, the user’s residency is stored as a two-letter abbreviation (e.g. KS), but the

Navjot Singh – 9625544280 7827675929


64

form select box should display the full state name (e.g. Kansas). To create such a select
box in Struts 2, you would use this code

Struts 2 Select Tag Object Backed

<s:select key="personBean.residency" list="states" listKey="stateAbbr" listValue="sta


teName" />

The list value tells the framework to call the getStates method of the EditAction class.
That method returns an ArrayList of State objects. Each State object has getStateAbbr
and getStateName methods.

The listKey attribute tells the framework to use the value returned by calling the
getStateAbbr method as the value for the value attribute of the HTML option tag and the
value returned by calling the getStateName method as the value displayed to the user.
So the above Struts 2 select tag code results in this HTML.

HTML Created By Struts 2 Select Tag

<tr>
<td class="tdLabel">
<label for="save_personBean_residency" class="label">State resident:</label>
</td>
<td>
<select name="personBean.residency" id="save_personBean_residency">
<option value="AZ">Arizona</option>
<option value="CA">California</option>
<option value="FL">Florida</option>
<option value="KS" selected="selected">Kansas</option>
<option value="NY">New York</option>
</select>
</td>
</tr>

The value returned by calling the personBean object’s getResidency method


determines which of the select tag’s option tags is marked as selected. In our example,
since getResidency returns ―KS‖, the option tag whose value attribute equals ―KS‖ is
marked as selected.

Struts 2 Checkbox Tag


Navjot Singh – 9625544280 7827675929
65

The Struts 2 checkbox tag is used to create the HTML input type equals checkbox tag.
The value for the key attribute tells the framework what method to call to determine if
the checkbox is checked or not checked. The method called should return a Boolean
value (true or false). A return value of true will cause the checkbox to be checked and
false the checkbox will not be checked.

Struts 2 Checkbox Tag

<s:checkbox key="personBean.over21" />

Since the method isOver21 returns true, the checkbox is checked.

HTML Created By Struts 2 Checkbox Tag

<tr>
<td valign="top" align="right"></td>
<td valign="top" align="left">
<input type="checkbox" name="personBean.over21" value="true" checked="checked
" id="save_personBean_over21"/>
<input type="hidden" id="__checkbox_save_personBean_over21" name="__checkbox_
personBean.over21" value="true" />
<label for="save_personBean_over21" class="checkboxLabel">21 or older</label>
</td>
</tr>

When the form is submitted and the checkbox is not checked, no value will be posted
for the checkbox (this is how HTML forms work). Since the Struts 2 framework will need
to update the value of the personBean’s over21 instance field to false—given that the
check box was not checked—the framework needs a way to determine if the checkbox
was not checked after form submission.

If you examine the HTML code created by the Struts 2 checkbox tag, you’ll see that it
created a hidden field associated with the personBean.over21 checkbox. When the
Struts 2 framework intercepts the submission of this form it will use this hidden form
field to check if the associated checkbox field exists in the posted form data. If that
checkbox field doesn’t exist then the Struts 2 framework will know to update the value of
the personBean object’s over21 instance variable to false.

Struts 2 checkboxlist Tag


The Struts 2 framework provides a unique form field control that creates a series of
associated check boxes, one or more of which can be checked. In the example

Navjot Singh – 9625544280 7827675929


66

application, the Person class has an Array of Strings, which is used to store car models
owned by a person.

Using the Struts 2 checkbox tag, we can create a series of checkboxes, one for each
possible car model the user may own. The value of each String in the personBean’s
carModels Array will determine which checkboxes are checked.

Struts 2 Checkboxlist Tag

<s:checkboxlist key="personBean.carModels" list="carModelsAvailable" />

The list attributes value in the checkboxlist tag tells the Struts 2 framework which
method to call to get the possible car models. In the example application, the framework
will call the EditAction class’s getCarModelsAvailable method. That method returns an
Array of Strings. For each element of the Array, the Struts 2 framework creates a
checkbox (including the associated hidden field described above).

The key attribute value in the checkboxlist tag tells the Struts 2 framework which
method to call on the personBean object to determine which checkboxes should be
checked. In the example application, the framework will call the personBean object’s
getCarModels method. The getCarModels method returns an Array of Strings. For each
String value in that Array that matches a String value in the Array returned by the
EditAction class’s getCarModelsAvailable, the checkbox will be checked.

HTML Created By Struts 2 Checkboxlist Tag

<tr>
<td class="tdLabel">
<label for="save_personBean_carModels" class="label">Car models owned:</label
>
</td>
<td>
<input type="checkbox" name="personBean.carModels" value="Ford" id="personBea
n.carModels-1" checked="checked"/>
<label for="personBean.carModels-1" class="checkboxLabel">Ford</label>

<input type="checkbox" name="personBean.carModels" value="Chrysler" id="perso


nBean.carModels-2"/>

<label for="personBean.carModels-2" class="checkboxLabel">Chrysler</label>

Navjot Singh – 9625544280 7827675929


67

<input type="checkbox" name="personBean.carModels" value="Toyota" id="personB


ean.carModels-3"/>
<label for="personBean.carModels-3" class="checkboxLabel">Toyota</label>

<input type="checkbox" name="personBean.carModels" value="Nissan" id="personB


ean.carModels-4" checked="checked"/>
<label for="personBean.carModels-4" class="checkboxLabel">Nissan</label>
<input type="hidden" id="__multiselect_save_personBean_carModels" name="__mul
tiselect_personBean.carModels" value="" />
</td>
</tr>

Summary
There are several other Struts 2 form controls you should explore. If you need more
information about the Struts 2 form tags consult the Struts 2 documentation
at http://struts.apache.org.

Navjot Singh – 9625544280 7827675929


68

Form Validation Using XML

 Introduction
 Example Application
 Validation Using XML
 XML Validator Format
 Validating An Email Address
 Validating A User’s Input Using A Regular Expression
 Validating A User’s Input Using An OGNL Expression
 Summary

The example code for this tutorial, form-xml-validation, is available for checkout
at struts-examples

Introduction
In this tutorial we’ll cover how to validate a user’s input in form fields using Struts 2’s
XML validation methodology. In the Form Validation tutorial we discussed validating a
user’s input using the validate method in the Action class. Using a separate XML
validation file gives you the ability to use validators built-in to the Struts 2 framework.

The Struts 2 user mailing list is an excellent place to get help. If you are having a
problem getting the tutorial example applications to work search the Struts 2 mailing list.
If you don’t find an answer to your problem, post a question on the mailing list.

Example Application
The example application that supports this tutorial shows how to use Struts 2’s XML
validation methodology. The information that can be edited is encapsulated in an object
of class Person.

To enable the user to edit his information that is stored in the Person object, we have
this form:

Navjot Singh – 9625544280 7827675929


69

When the user submits the form, we want to validate his entries into the form fields.

Validation Using XML


To validate a user’s form field entries you can use a separate XML file that contains
your validation rules. The XML file that contains the validation rules must be named as
ActionClassName-validation.xml. In the example application, the XML validation file is
named EditAction-validation.xml (see src/main/resources/org/apache/struts/edit/action).

Struts 2 provides several different validators that you can use in the XML validation file.
See Validation for a list of validators you can employ.

In the above form, we want to ensure the user enters a first name. To have the Struts 2
framework enforce that rule we can use the Struts 2 requiredstring validator. This
validator checks that the user has entered a string value in the form field.

XML Validator Format


In the XML validation file (for this example that is EditAction-validation.xml), is this XML:

XML Validator Required String

<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.3//EN" "http://str


uts.apache.org/dtds/xwork-validator-1.0.3.dtd">

Navjot Singh – 9625544280 7827675929


70

<validators>
<validator type="requiredstring">
<param name="fieldname">personBean.firstName</param>
<message>First name is required.</message>
</validator>
</validators>

Within the validators node you can have 1 or more validator nodes. The type attribute
specifies which validator you want the Struts 2 framework to use (see Validation ). The
param name=‖fieldname‖ node is used to tell the framework which form field entry to
apply the rule to. See edit.jsp for the form fields and their name value (review Struts 2
Form Tags if you’re not familiar with how to use Struts 2 form tags). The message node
is used to tell the framework what message to display if the validation fails.

There are alternate ways to write the XML that goes in the validation XML file. See Validation in
the Struts 2 documentation for a full discussion.

For example if the user doesn’t enter a value in the first name form field and clicks on
the Save Changes button, he will see the following.

Validating An Email Address


You can use the Struts 2 email validator to validate the user’s input in the email field.
Here is the validator node that is in the EditAction-validation.xml file.

Email Validator

<validator type="requiredstring">
<param name="fieldname">personBean.email</param>
<message>Email address is required.</message>

Navjot Singh – 9625544280 7827675929


71

</validator>
<validator type="email">
<param name="fieldname">personBean.email</param>
<message>Email address not valid.</message>
</validator>

Note that in the example, we are requiring the user to enter an email address and then
validating the email address the user entered.

Validating A User’s Input Using A Regular Expression


The Struts 2 framework provides a powerful way to validate a user’s form field input by
using the regex validator . In the example application, we want to ensure the user enters
the phone number in the format 999-999-9999. We can use a regular expression and
the regex validator to enforce this rule.

REGEX Validator

<validator type="requiredstring">
<param name="fieldname">personBean.phoneNumber</param>
<message>Phone number is required.</message>
</validator>
<validator type="regex">
<param name="fieldname">personBean.phoneNumber</param>
<param name="regex"><![CDATA[\d{3}-\d{3}-\d{4}]]></param>
<message>Phone number must be entered as 999-999-9999.</message>
</validator>

The param name="regex" node is used to specify the regular expression that will be
applied to the user’s input. Note how the regular expression is contained within a
CDATA section.

Validating A User’s Input Using An OGNL Expression


In the example application, we want to ensure the user checks at least one of the car
model check boxes. To enforce this rule we can use the fieldexpression validator .
Here’s the XML for that validator node.

FieldExpression Validator

Navjot Singh – 9625544280 7827675929


72

<validator type="fieldexpression">
<param name="fieldname">personBean.carModels</param>
<param name="expression"><![CDATA[personBean.carModels.length > 0]]></param>
<message>You must select at least one car model.</message>
</validator>

The param name=‖expression‖ node contains an OGNL expression that evaluates to


true or false. We haven’t previously discussed OGNL, which stands for Object-Graph
Navigation Language (see https://github.com/jkuhnert/ognl and OGNL ). OGNL
expressions can be evaluated by the Struts 2 framework as Java statements.

In the above XML the value of the param name=‖expression‖ node,


personBean.carModels.length > 0, will be evaluated by the framework as a Java
statement. The part personBean.carModels tells the framework to call the getCarModels
method of class Person. That method returns an Array. Since class Array has a length
attribute, the framework will get the value of the length attribute of the Array returned by
the getCarModels method.

If the user did not check any of the check boxes, the Array returned by the
getCarModels method will have a length value of 0. Since the complete OGNL
expression will only evaluate to true if the length value is greater than 0, the validation
fails. The user will see this.

The fieldexpression validator is useful when doing conditional validation of a user’s


input. If the OGNL expression doesn’t evaluate to true then the user’s input won’t be
allowed.

Summary
The Struts 2 framework provides easy-to-use validation methodologies. You can add a
validate method to the Action class or have a separate XML file with validation rules or
you can use a combination of both methodologies.

Navjot Singh – 9625544280 7827675929


73

Control Tags

 Introduction
 Struts 2 if Tag
 Struts iterator Tag
 Additional Iterator Attributes

The example code for this tutorial, control-tags, is available at struts-examples

Introduction
Struts 2 has several control tags that can be used in the view. This tutorial will discuss
and show examples of how to use the Struts 2 if and iterator tags. For more information
about these and other control tags visit tags reference.

The Struts 2 user mailing list is an excellent place to get help. If you are having a
problem getting the tutorial example applications to work search the Struts 2 mailing list.
If you don’t find an answer to your problem, post a question on the mailing list.

Struts 2 if Tag
In the example application’s thankyou.jsp is this markup.

thankyou.jsp Struts if Tag

<s:if test="personBean.over21">
<p>You are old enough to vote!</p>
</s:if>
<s:else>
<p>You are NOT old enough to vote.</p>
</s:else>

The Struts if tag has a test attribute. The value of the test attribute must evaluate to true
or false. If true the statements between the opening and closing s:if tags will be
executed. If false, the statements between the opening and closing s:else tags will be
executed. Note that s:else tags come after the closing s:if tag and that the s:else tags
are not required.

In the above example the Struts framework will call method getPersonBean exposed by
the Action class (EditAction.java). Using the Person object returned by that method, the
framework will then call method isOver21 of class Person. That method returns a
boolean that will be used to determine if the test is true or false.

Navjot Singh – 9625544280 7827675929


74

The value of the test attribute must be an expression that evaluates to true or false, but
doesn’t need to be a method call that returns a boolean. For example this s:if tag that is
in thankyou.jsp has a more complicated expression.

<s:if test="personBean.carModels.length > 1">


<p>Car models
</s:if>
<s:else>
<p>Car model
</s:else>

The purpose of the above markup is to use either ―Car model‖ or ―Car models‖
depending on how many car models the user selected on the edit page. So the value for
the test attribute of this iterator tag gets the length of the carModels String array and
compares that to 1. If it’s greater than 1, the correct grammar is ―Car models‖ else the
correct grammar is ―Car model‖.

Struts iterator Tag


The Struts iterator tag is used to generate a loop that iterates over each item in a
collection. In the thankyou.jsp is this markup.

<table style="margin-left:15px">
<s:iterator value="personBean.carModels">
<tr><td><s:property /></td></tr>
</s:iterator>
</table>

The goal of this code is to create an HTML table with a row that display a car model
selected by the user on the edit page. The car models the user selects on the edit page
are stored in the carModels field (a String array) of the personBean object (of class
Person).

The iterator tag has a value attribute that must evaluate to a collection (Array, List,
Map).

The s:property tag nested inside the iterator tag is used to display the specific value of
the collection each time the iterator loops over an element of the collection. Since the
collection is an Array of String objects, the s:property tag doesn’t need to specify a
value attribute. By default the s:property tag will display the single String for that
element of the collection.

Navjot Singh – 9625544280 7827675929


75

If the collection contains objects that have multiple fields, then you should use the value
attribute of the s:property tag to determine what field to display. For example:

<table style="margin-left:15px">
<s:iterator value="states" >
<tr><td><s:property value="stateAbbr" /></td> <td><s:property value="stateNam
e" /></tr>
</s:iterator>
</table>

The value of the iterator tag is states, which causes the Struts 2 framework to call the
getStates method of the Action class (EditAction.java). The getStates method returns
a List of State objects. The State class has two fields stateAbbr and stateName, both
having the appropriate get method. The iterator will loop over each State object stored
in the collection. Each time through the loop, the Struts 2 framework will have a
reference to the current State object and will call getStateAbbr and getStateName
methods for that current State object.

Additional Iterator Attributes


The Struts 2 iterator tag has additional attributes you can use to control the begin and
end values for specifying that the iterator tag should only loop over a part of the
collection. See the iterator tag reference for more information.

Navjot Singh – 9625544280 7827675929


76

Wildcard Method Selection

 Introduction
 Example Application
 Wildcard Method Selection
 Dynamic Method Invocation
 Summary

The example code for this tutorial, wildcard-method-selection, is available for


checkout at struts-examples

Introduction
In this tutorial we’ll cover how to configure an action node in the struts.xml configuration
file so that one action node can be used to relate several different Action URLs to
specific methods of the Action class. This will reduce the number of action nodes we
must write in the struts.xml configuration file.

The Struts 2 user mailing list is an excellent place to get help. If you are having a
problem getting the tutorial example applications to work search the Struts 2 mailing list.
If you don’t find an answer to your problem, post a question on the mailing list.

Example Application

The example application that supports this tutorial shows how to use Struts 2’s wildcard
method selection methodology. The example application is just a simple one that lists
some people and lets you edit them, delete them, and add a new person to the list.
Everything that the application needs to do with a Person (the model class) is controlled
by the Struts 2 ActionSupport class PersonAction. The PersonAction class has several
different methods (e.g. create, edit, delete) that are called depending on what the user
wants to do.

Wildcard Method Selection

Navjot Singh – 9625544280 7827675929


77

Without using the wildcard method selection technique, I’d have to write an action
mapping node in the Struts 2 configuration file for each separate action I’d want to call.
For example:

Struts.xml Action Configuration

<action name="createPerson" class="org.apache.struts.tutorials.wildcardmethod.action.


PersonAction" method="create">
<result name="input">input.jsp</result>
<result name="success">view.jsp</result>
</action>

<action name="editPerson" class="org.apache.struts.tutorials.wildcardmethod.action.Pe


rsonAction" method="edit">
<result name="input">input.jsp</result>
<result name="success">view.jsp</result>
</action>

So even for this simple application, I’d have to write four separate action mapping nodes
(create, edit, delete, saveOrUpdate) in the configuration file. So you can easily see that
a more complex application can have dozens of action mapping nodes.

To implement the wildcard method selection technique to enable the Struts 2 framework
to dynamically select the correct method to call at runtime you just need to use the
wildcard character, *, in your name value and an attribute value place holder ( {1} ) for
the method value. For example:

Struts.xml Action Configuration Using Wildcard Method Selection

<action name="*Person" class="org.apache.struts.tutorials.wildcardmethod.action.Perso


nAction" method="{1}">
<result name="success">view.jsp</result>
<result name="input">input.jsp</result>
</action>

The * is the wildcard character. Any action name values that end in ―Person‖ will be
handled by this action mapping. Whatever value is before ―Person‖ will be the value
used for the method attribute (the {1} place holder will be replaced with that value). For
example this URL:

http://localhost:8080/wildcard-method-selection/createPerson.action

Navjot Singh – 9625544280 7827675929


78

will be be processed by the the above action mapping and method create of class
PersonAction will be called. While this URL

http://localhost:8080/wildcard-method-selection/deletePerson.action

will cause the delete method of class PersonAction to be called.

What happens if we have a URL with nothing in front of Person? For example:

http://localhost:8080/wildcard-method-selection/Person.action

If there is no value in front of Person, then the Struts 2 framework will call the execute
method of the class PersonAction.

Dynamic Method Invocation


The wildcard method selection technique explained above should not be confused with
the ―Dynamic Method Invocation‖ technique. The Struts 2 documentation explains this
technique (which uses the bang, !, operator in the action name) and recommends
against using the ―Dynamic Method Invocation‖ technique due to security and other
reasons related to how this technique is implemented internally.

The Struts 2 documentation also recommends turning off the option to use the dynamic
method invocation by setting struts.enable.DynamicMethodInvocation to FALSE in the
Struts configuration.

Summary
By using the wildcard method selection technique explained above, you can significantly
reduce the number of action mapping nodes you need to write and manage in the Struts
2 XML configuration file.

Navjot Singh – 9625544280 7827675929


79

Themes

 Introduction
 Specifying The Theme Struts 2 Should Use
 Specifying The CSS Used By The Struts 2 Tag
 Creating And Applying Your Own Themes For Struts 2 Tags
 Summary

The example code for this tutorial, themes, is available for checkout at struts-examples

Introduction
When you use a Struts 2 tag such as s:select in your web page, the Struts 2
framework generates HTML that styles the appearance and controls the layout of the
select control. The style and layout is determined by which Struts 2 theme is set for the
tag. Struts 2 comes with three built-in themes: simple, xhtml, and css_xhtml. If you
don’t specify a theme, then Struts 2 will use the xhtml theme by default.

The Struts 2 user mailing list is an excellent place to get help. If you are having a
problem getting the tutorial example applications to work search the Struts 2 mailing list.
If you don’t find an answer to your problem, post a question on the mailing list.

For example, this Struts 2 select tag:

Struts 2 Select Tag

<s:select key="personBean.sport" list="sports" />

generates this HTML markup:

HTML Created By Struts 2 Select Tag

<tr>
<td class="tdLabel">
<label for="save_personBean_sport" class="label">Favorite sport:</label>
</td>
<td>
<select name="personBean.sport" id="save_personBean_sport">
<option value="football">football</option>
<option value="baseball">baseball</option>
<option value="basketball" selected="selected">basketball</option>
</select>

Navjot Singh – 9625544280 7827675929


80

</td>
</tr>

Notice how the HTML generated uses table tags to control the layout of the label and
select HTML. There is also a class, tdLabel, applied to the table column where the label
tag is rendered. Since no theme was specified for the Struts 2 select tag the
default xhmtl theme was used.

Specifying The Theme Struts 2 Should Use


The Struts 2 tags have a theme attribute you can use to specify which Struts 2 theme
should be used when creating the HTML for that tag. The values for the theme attribute
are simple, xhtml, css_xhtml, and ajax. To learn more about these themes
visit Themes and Templates Documentation. This tutorial will review
the xhtml, css_xhtml, and the simple themes. The ajax theme is a special theme used
for ajax operations (see Ajax Theme in the documentation).

You can specify the theme on a per Struts 2 tag basis or you can use one of the
following methods to specify what theme Struts 2 should use:

1. The theme attribute on the specific tag


2. The theme attribute on a tag’s surrounding form tag
3. The page-scoped attribute named theme
4. The request-scoped attribute named theme
5. The session-scoped attribute named theme
6. The application-scoped attribute named theme
7. The struts.ui.theme constant in struts.xml (defaults to xhtml)

Consult Selecting Themes for how to set the theme using the above approaches.

In the example application, examine edit.jsp. The theme attribute of the form tag is set
to xhtml. Run the application (see the readme.txt file) and view the source for edit.jsp
after it is rendered in your browser. You should see the form HTML tags layout
controlled by table tags.

Change the theme to simple for the form’s theme attribute and redeploy the application.
Examine the source for edit.jsp after it is rendered in the browser. You should see that
there are no table tags controlling the layout and also there are no label tags for the text
fields.

Change the theme to css_xhtml for the form’s theme attribute and redeploy the
application. Examine the source for edit.jsp after it is rendered in the browser. The
layout of the form tags is now controlled by div tags and the label tags are back.

Specifying The CSS Used By The Struts 2 Tag


Navjot Singh – 9625544280 7827675929
81

Change the theme attribute for the form tag back to xhtml. Notice when you view the
source of edit.jsp after it is rendered in the browser that there is a class named tdLabel
applied to the table column that contains the label. This CSS class controls the position
of the label in the table column. The tdLabel style is defined
in /themes/struts/xhtml/styles.css. The link to this style sheet was included in
edit.jsp’s head section when you add the s:head tag to edit.jsp.

Load this style sheet in your browser (in the example application the link
is http://localhost:8080/themes/struts/xhtml/styles.css if your Servlet container is running
on localhost, port 8080). You’ll see the following:

styles.css

.label {font-style:italic; }
.errorLabel {font-style:italic; color:red; }
.errorMessage {font-weight:bold; color:red; }
.checkboxLabel {}
.checkboxErrorLabel {color:red; }
.required {color:red;}
.tdLabel {text-align:right; vertical-align:top; }

So the .label selector renders the label tag’s text in italic. The .tdLabel tag specifies that
the text should align to the right and top of the table column.

You can override the above selectors by including the same selectors in your page’s
head section. For example add the following to the head section of edit.jsp.

Override Label Style

<style type="text/css">
.label {color:blue; font-style:normal; font-weight:bold}
</style>

Now the label tag will render the text in blue, bold, normal (not italics) style.

Creating And Applying Your Own Themes For Struts 2


Tags
The theme templates (simple, xhtml, css_xhtml) can be found in the Struts 2 core jar
file. If you expand (extract the files) the Struts 2 core jar file you’ll find folders
named template.css_xhtml, template.simple, and template.xhtml. Those folders
contain the templates for the three default Struts 2 themes. In each folder is a file for
Navjot Singh – 9625544280 7827675929
82

each Struts 2 tag. For example if you expand the template.xhtml folder you’ll see
the select.ftl file.

The Struts 2 framework uses the FreeMarker template engine to generate the HTML for
the Struts 2 tags. That’s why the file extension is .ftl. You can learn more about
FreeMarker by visiting https://freemarker.apache.org/.

Also in the template.xhmtl folder is the styles.css file. This is the styles.css file that
your application will use if it uses the xhtml theme.

Let’s say we wanted to create our own theme that will change how the Struts 2
checkboxlist tag displays the checkboxes and their labels.

In the example application I’ve extended the default XHMTL theme (see
file theme.properties under src/main/resources/template/KUTheme ).
The checkboxlist.ftl theme that is part of the XHTML theme only includes a space
between each label and the next checkbox (see checkboxlist.ftl in
the template/simple folder in Struts 2 core). That is why all the checkboxes are
displayed across the width of the browser window. For my custom checkboxlist theme I
want to have a break tag after each label tag so that each checkbox and its label will be
on their own line.

In the example application there is a folder


named src/main/resources/template/KUTheme . In that folder is a checkboxlist.ftl,
the contents of which I originally copied from the checkboxlist.ftl that is in
the templates.xhtml folder from the Struts 2 core jar.

I then modified the checkboxlist.ftl in the KUTheme folder to be:

Modified checkboxlist.ftl

<#include "/${parameters.templateDir}/${parameters.expandTheme}/controlheader.ftl" />

<#include "/${parameters.templateDir}/KUTheme_simple/checkboxlist.ftl" />

<#include "/${parameters.templateDir}/${parameters.expandTheme}/controlfooter.ftl" />


<#nt/>

Be sure to note the change to the second line—using KUTheme_simple in the path.

Then in the example application I created a KUTheme_simple folder


under src/main/resources/template (optionally you can place it under webapp,
e.g. src/main/webapp/template ). In that folder I created checkboxlist.ftl and copied
the contents from template.simple checkboxlist.ftl (again found in the Struts 2 core
jar). After copying the contents to checkboxlist.ftl that is in KUTheme_simple folder, I

Navjot Singh – 9625544280 7827675929


83

modified checkboxlist.ftl so that the label tag has a style of red bold text and I added
a break tag after each label so that each check box and label will be on its own line.

Since the XHTML theme is the default theme and I have a theme.properties file
defined with parent = xhtml, the KUTheme will inherit all the themes from xhmtl except
for the theme for the checkboxlist tag since my KUTheme includes a definition for that
tag’s layout. In the struts.xml file (src/main/resources) you will see that the I’ve
specified the default theme to be KUTheme.

In the deployed web application, Struts 2 will first look for a tag’s template on the
application’s class path and if it doesn’t find the template there it will use the default
template that is part of the Struts 2 core jar. Since we’ve added a template folder to the
application’s web root, now when Struts 2 creates the HTML to display the checkboxlist
tag it will use the template that is in the KUTheme folder (which tells it to use
the checkboxlist.ftl file that is in the KUTheme_simple folder instead of the one in
the template.simple folder that is part of the Struts 2 core Jar).

After redeploying the application the check boxes for the Car Models Owned should
appear like:

Summary
You can easily override the default theme used by Struts 2 to control the appearance
and layout of a Struts 2 tag. Each Struts 2 tag has an associated template file
(e.g. select.ftl) that is in a folder named after the theme (e.g. xhtml). By default the
Struts framework will look in the Struts 2 core Jar file for the theme folder and
templates. However, if you include your own theme folder (e.g. KUTheme) under
webapp/template (or WebContent/template in the Ant version) and specify that folder
name (e.g. KUTheme) as the value for the theme attribute, then the Struts 2 framework
will look in that theme folder for the tag’s template.

To learn more about how to use the Struts 2 themes and how you can override them,
visit Themes and Templates Documentation .

Navjot Singh – 9625544280 7827675929


84

Spring and Struts 2

 Introduction
 Struts 2 Spring Plugin
 Spring Configuration File
 Alternative - Have Spring Manage Creation Of ActionSupport Class
 Summary

The example code for this tutorial, spring-struts, is available for checkout at struts-
examples

Introduction
In the execute method of many Struts 2 ActionSupport classes are statements that
create objects and then have those objects execute methods that perform needed
tasks. Whenever one class creates an object of another class that introduces a
dependency between the two classes. The Spring framework makes it easier for the
application developer to manage these dependencies and helps make the application
more flexible and maintainable. This tutorial will show you how to use Struts 2 and
Spring together to manage the dependencies between your ActionSupport classes and
other classes in your application.

This tutorial assumes you understand how to use the Spring framework to manage
dependencies between classes. You can learn more about Spring by reading the
documentation at https://spring.io/docs

The Struts 2 user mailing list is an excellent place to get help. If you are having a
problem getting the tutorial example applications to work search the Struts 2 mailing list.
If you don’t find an answer to your problem, post a question on the mailing list.

If you examine the example application for the Struts 2 Themes tutorial you’ll see this
code in the EditAction class

EditAction Class Hard-Coded Dependency

private EditService editService = new EditServiceInMemory();

The above statement hard-codes a dependency between the EditAction class and
the EditServiceInMemory class. This is poor design for two reasons.

1. If I need to replace the EditServiceInMemory with another class that implements


the EditService interface I’ll have to hunt down and replace all statements where I
hard-coded the dependency.
2. I cannot test EditAction without using the EditServiceInMemory class. I cannot
isolate EditAction by using a stub implementation of EditService when writing my
test case because the use of EditServiceInMemory is hard-coded.

Navjot Singh – 9625544280 7827675929


85

Spring provides a mechanism to manage dependencies by injecting them at run time.


Struts 2 ActionSupport classes—like any other Java class—can be injected with a
dependent object by the Spring framework. So instead of having the above code, I
would have this statement in EditAction.

EditAction Class No Hard-Coded Dependency

private EditService editService;

At run time the Spring framework will provide an object of a class that implements the
EditService interface.

Struts 2 Spring Plugin


Struts 2 provides a plugin that enables Spring to inject into the ActionSupport classes
any dependent objects you’ve specified in the Spring configuration file. Consult Spring
Plugin documentation for more information about how the plugin works.

For a Maven application you’ll need to add a dependency to the struts2-spring-plugin jar
(see the Maven example application for this tutorial). The plugin’s pom.xml includes
transitive dependencies to the Spring jar files.

The current version (2.5.10.1) of the Struts 2 Spring plugin has transitive dependencies
to the Spring 4.1.6.RELEASE version. If you want to use the latest version of Spring,
then you should exclude the transitive dependencies in your pom.xml for the Struts 2
Spring plugin and then declare dependency nodes to the current version of the Spring
jar files. If you are using Ant and explicitly including the jar files in your application, then
just include the latest version of the Spring jar files.

In your ActionSupport class you must have a set method for the dependent object that
follows standard Java bean naming conventions. If you examine the EditAction class
for this tutorial’s application you’ll see this set method.

public void setEditService(EditService editService) {


this.editService = editService;
}

Spring will use that set method to provide an object of type EditService to
the EditAction class at run time.

To make our application ―Spring aware‖ we need to add this line to web.xml.

Spring Listener In web.xml

Navjot Singh – 9625544280 7827675929


86

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-c
lass>
</listener>

The above code will activate the Spring framework when the application is started up by
the Servlet container. By default Spring will look for a configuration file name
applicationContext.xml in WEB-INF (consult the Spring documentation for how you can
change where Spring looks and what the configuration file name is).

Spring Configuration File


In the Spring configuration file we create a bean node for those objects we want Spring
to create an instance of and inject into our ActionSupport class. In the example
application is this applicationContext.xml.

Spring Configuration File

<?xml version="1.0" encoding="UTF-8"?>


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="editService" class="org.apache.struts.edit.service.EditServiceInMemory"


/>

</beans>

Note the id value above. By default the Spring plugin works with Spring to autowire the
dependencies of the ActionClass by name. Spring will create an object of class
EditServiceMemory and provide that object to any ActionSupport class that has a
setEditService method with an argument of type EditService. Consult the Spring
Plugin documentation for how to change the default autowire method.

The editService bean created by Spring will have a scope of singleton since that is the
default scope. Consult section 3.5 of the Spring documentation for how to configure the
bean definition to use a different scope (e.g. request or session).

Navjot Singh – 9625544280 7827675929


87

Alternative - Have Spring Manage Creation Of


ActionSupport Class
Using the above methodology, the Struts 2 framework will still manage the creation of
the ActionSupport class. If you prefer you can configure the application so that Spring
will create the ActionSupport class also. To support this technique you need to add a
bean node to the Spring configuration file for the ActionSupport class.

Spring Configuration For ActionSupport Class Managed By Spring

<?xml version="1.0" encoding="UTF-8"?>


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="editService" class="org.apache.struts.edit.service.EditServiceInMemory"


/>

<bean id="editAction" class="org.apache.struts.edit.action.EditAction" scope="pro


totype">
<property name="editService" ref="editService" />
</bean>

</beans>

Note in the above that there is an editAction bean and its editService property is set
to the editService bean. Since we are having Spring manage the EditAction class we
must specify any properties of EditAction that we want Spring to inject. Please
remember that actions must be created on each request, they cannot be singletons-
this is the default scope that’s why it must be changed to prototype.

In the struts.xml configuration file you must specify the Spring id value for the class
attribute of the action node. This tells Struts to get a bean with that id value from Spring
for the Action class.

Struts Configuration For Spring Managed ActionSupport Class

<action name="edit" class="editAction" method="input">

Navjot Singh – 9625544280 7827675929


88

<result name="input">/edit.jsp</result>
</action>

Summary
In this tutorial we reviewed how to use the Struts 2 Spring plugin to integrate Spring and
Struts. By using the Struts 2 Spring plugin you can have Spring manage the
dependencies of your ActionSupport classes. Of course you can also take advantage of
the many other benefits (AOP, Spring JDBC) that the Spring framework provides.

Navjot Singh – 9625544280 7827675929


89

Annotations

 Introduction
 Struts 2 Convention Plugin
 Struts 2 Configuration Plugin
 Annotations
 Struts 2 Configuration Values
 Summary

The example code for this tutorial, annotations, is available for checkout at struts-
examples

Introduction
In our previous tutorials we’ve been using an XML file (struts.xml) to configure our
applications. The XML file wires up the action names (register), with ActionSupport
classes (RegisterAction.java), and with the result to render back to the browser
(register.jsp). Struts 2 provides an alternative to using XML to configure your
application by using standard naming conventions and annotations for your action
names, ActionSupport classes, and results.

This tutorial assumes you understand how to apply annotations to Java classes and
methods. If you’re not familiar with annotations, consult the Java online tutorial.

The Struts 2 user mailing list is an excellent place to get help. If you are having a
problem getting the tutorial example applications to work search the Struts 2 mailing list.
If you don’t find an answer to your problem, post a question on the mailing list.

Struts 2 Convention Plugin


Struts 2 enables the use of standard naming conventions and annotations when you
include the Convention plugin in your application’s class path. If you’re using Maven
you’ll need to add a dependency:

Convention Plugin Dependency

<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-convention-plugin</artifactId>
<version>X.X.X.X</version>

</dependency>

Navjot Singh – 9625544280 7827675929


90

If you’re using Ant then copy the struts2-convention-plugin jar file from the Struts 2
download to your WEB-INF/lib folder.

The convention plugin provide several different ways you can configure your Struts 2
application without using XML. Consult the Convention Plugin documentation for
complete details. This tutorial only examines one simple way of following the
conventions provided by the Convention plugin.

When you run the example application you’ll see on the index.jsp page a link to Get
your hello. This URL for the link is hello.action. When you click on this link, the
execute method of class HelloAction.java (which is a Struts 2 ActionSupport class) is
run. The view page rendered back to the browser after the execute method returns
success is hello-success.jsp.

None of the above is wired up using XML but rather happens because the application
follows the standard naming conventions expected by the Convention plugin. The first
convention is that the ActionSupport class, HelloAction.java, is in
package org.apache.struts.struts2annotations.action . One of the Convention
plugin’s defaults is to look for ActionSupport classes that are in package structure that
ends in action. The next convention the application follows is
that HelloAction.java extends the ActionSupport class and defines an execute
method. The link is hello.action. When the Struts 2 filter sees a request for hello.action it
will map that request to the HelloAction class’s execute method due to the Convention
plugin being used.

So a link of hello.action causes the execute method of class HelloAction to be run. That
method returns success. Because the application is using the Convention plugin, Struts
2 will render back to the browser a view page named hello-success.jsp that is located
in WEB-INF/content (by default the Convention plugin expects all view pages to be in
this location). If the execute method returns ―input‖ or ―error‖ then the view page
rendered would have been hello-input.jsp or hello-error.jsp.

Struts 2 Configuration Plugin


In a previous tutorial we reviewed how to use the Struts 2 Configuration plugin to view
the details of how Struts 2 has configured your application. When using the Convention
plugin, it’s very handy to also use the Configuration plugin during development. On the
example application’s home page is a link to the application’s configuration. Click on
that link and then the hello link on the left menu (under Actions in default). You’ll see the
configuration for the hello action including it’s Action class, result, and view page.

Navjot Singh – 9625544280 7827675929


91

Annotations
If you want to go beyond the simple naming conventions provided by the Convention
plugin, you can use the Struts 2 annotations also provided by the plugin. For example, a
common work-flow for a Struts 2 application is to first execute the ActionSupport class’s
input method to setup form field default values and then to run the execute method of
the same ActionSupport class when the form is submitted (to validate and save the
user’s input).

The link to Register for the drawing on the example application’s home page follows this
work flow. The link value is register-input.action. If you examine the
RegisterAction.java class you’ll find the input method with an Action annotation.

Action Annotation

@Action("register-input")
public String input() throws Exception {
logger.info("In input method of class Register");

return INPUT;
}

The Action annotation tells Struts 2 to execute the annotated method when the action
link value equals the Action annotation’s value (register-input). So a link of register-
input.action will call the input method of class RegisterAction. On the example
application’s home page is a link to Register for the drawing with a URL of register-
input.action.

Navjot Singh – 9625544280 7827675929


92

The input method above returns ―input‖. By the standards of the Convention plugin, the
view page rendered will be register-input.jsp (from WEB-INF/content). On that view
page is a Struts 2 form tag with an action attribute value of register. When submitting
the form, the execute method of class RegisterAction will be run. Since the execute
method returns success, the view page rendered is register-success.jsp.

Struts 2 Configuration Values


In previous examples, we included in struts.xml values for some of the Struts 2
configuration parameters.

struts.xml parameter configuration

<constant name="struts.devMode" value="true" />

When we don’t use a struts.xml file, we can set the value of these Struts 2 parameters
by using filter parameters in web.xml:

Struts 2 Parameter Configuration web.xml

<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter<
/filter-class>
<init-param>
<param-name>struts.devMode</param-name>
<param-value>true</param-value>
</init-param>
</filter>

Summary
We’ve just scratched the surface of what the Struts 2 convention plugin provides to
reduce or eliminate the need to use an XML file to configure your Struts 2 application.
The Struts 2 Convention plugin provides ways to map multiple actions to the same
method, map results to different view pages, map errors to view pages, and much more.
Be sure to read through the Convention Plugin documentation for alternative ways to
configure your Struts 2 application.

Navjot Singh – 9625544280 7827675929


93

Introducing Interceptors

 Introduction
 Introducing Interceptors
 Run The Example
 Create Your Own Interceptor
 Summary

The example code for this tutorial, interceptors, is available at struts-examples

Introduction
So far our tutorials have not delved into the inner workings of the Struts 2 framework.
But in this tutorial we’ll introduce a key set of classes the Struts 2 framework relies upon
to do most of the work whenever an Action is executed. In this tutorial’s example project
there is a register link that is mapped in the Struts XML configuration file (struts.xml) to
the execute method of class Register. Before that execute method is called much work
is done behind the scenes by the Struts 2 framework. For example:

1. Handling any exceptions generated


2. Converting the String request parameters to the Register class’s instance fields where
the name values match
3. Calling the validate method and/or the external XML validation

After the execute method is completed more work must be done

1. Handling any exceptions generated


2. Converting the Register class’s instance fields to String values for display in the view
page
3. Forwarding to the correct view page depending on the result String returned by the
execute method

The above list of tasks are not complete - several other tasks are done before and after
the execution of the Action.

The benefit of using Struts 2 is all this work happens automatically. You can focus on
the logic of the controller (the Struts 2 ActionSupport class), the Service layer, the data
access layer, your domain models, etc.

The Struts 2 user mailing list is an excellent place to get help. If you are having a
problem getting the tutorial example applications to work search the Struts 2 mailing list.
If you don’t find an answer to your problem, post a question on the mailing list.

Introducing Interceptors

Navjot Singh – 9625544280 7827675929


94

The tasks that are done by the Struts 2 framework before and after an Action is
executed are done by Struts 2 interceptors. Interceptors are standard Java classes
included in the Struts 2 core jar which are executed in a specific order.

In our example application there is a package node in struts.xml. The package node has
an attribute of extends with a value of ―struts-default.‖ The value ―struts-default‖
identifies to the framework the specific stack of interceptors that will be executed before
and after the Actions in that package.

If you want to learn more about the inner workings of interceptors, what interceptors
belong to the struts default stack, and what are all the interceptors included with Struts
2, visit Understanding Interceptors .

Sometime the Struts 2 default stack of interceptors are not exactly what you need for a
particular action. You may want to use interceptors that are not part of the Struts 2
default stack. For an individual Action or for the entire package of Actions, you can
specify a different stack of interceptors that the Action or package should use. Below is
how you would specify that the register Action should use both
the logger and timer interceptors in addition to the interceptors provided by the default
stack.

Specify Specific Interceptors For An Action

<action name="register" class="org.apache.struts.register.action.Register" method="ex


ecute">
<interceptor-ref name="timer" />
<interceptor-ref name="logger" />
<interceptor-ref name="defaultStack">
<param name="exception.logEnabled">true</param>
<param name="exception.logLevel">ERROR</param>
</interceptor-ref>
<result name="success">thankyou.jsp</result>
<result name="input">register.jsp</result>
</action>

The logger interceptor logs the start and end of the execution of an Action. The timer
interceptor logs the amount of time (in milliseconds) for execution of the Action. These
two interceptors used together can provide developers useful feedback.

In the code example above note the three interceptor-ref nodes. Each one has a value
for the name attribute. For the register Action we are instructing the framework to use
the timer, logger, and defaultStack interceptors. The defaultStack are all the
interceptors normally executed for an Action.

Navjot Singh – 9625544280 7827675929


95

How did I know to use the value of timer for the name attribute and even that there is a
timer interceptor? On the Interceptors web page in the Struts 2 documentation are a list
of interceptors that come with the Struts 2 framework and what the name value is for
each interceptor.

How did I know that the timer interceptor isn’t part of the defaultStack of interceptors
already? Again on the Interceptors documentation web page is a list of which
interceptors belong to the defaultStack.

Note the param nodes. These nodes are used to provide a value to the setLogEnabled
and setLogLevel methods of the Exception Interceptor. Providing the values of true and
ERROR will cause the Struts 2 framework to log any exceptions not caught by the
application’s code and to log those exceptions at the ERROR level.

Run The Example


In the example application follow the README instructions to build, deploy, and run the
application. View the output sent to the JVM console to see the log messages
generated by the logger and timer interceptors. You should see log messages similar to
the following:

INFO: Starting execution stack for action //register


Nov 20, 2010 9:55:48 AM com.opensymphony.xwork2.util.logging.jdk.JdkLogger info
INFO: Finishing execution stack for action //register
Nov 20, 2010 9:55:48 AM com.opensymphony.xwork2.util.logging.jdk.JdkLogger info
INFO: Executed action /register!execute took 177 ms.

If you wanted to have the logger and timer interceptors executed for all Actions in a
package you would use the following in struts.xml:

Specify Specific Interceptors For A Package

<package name="basicstruts2" extends="struts-default" >


<interceptors>
<interceptor-stack name="appDefault">
<interceptor-ref name="timer" />
<interceptor-ref name="logger" />

<interceptor-ref name="defaultStack" />

</interceptor-stack>
</interceptors>

Navjot Singh – 9625544280 7827675929


96

<default-interceptor-ref name="appDefault" />

<!-- rest of package omitted -->

</package>

In the code above we use the interceptors node to define a new stack of interceptors
that includes the timer, logger, and defaultStack interceptors. We give this new
interceptor stack a name of appDefault. Then we use the default-interceptor-
ref node to specify that for all Actions defined inside this package node
the appDefault stack of interceptors are to be used. Thus
the timer and logger interceptor will be executed for each Action in this package.

Note that in both examples we are still executing all the other interceptors by including
the defaultStack as one of the interceptor-ref nodes. When you specify what
interceptors you want to use for an Action or a package then only those interceptors are
executed. So if in the example we had left out the interceptor-
ref for defaultStack only the logger and timer interceptors would have executed.

Create Your Own Interceptor


In addition to specifying your own stack of interceptors, you can also write your own
new interceptor and add it to the stack that is executed. The Struts Writing
Interceptors guide explains how to do this. For example, you could create your own
interceptor to handle authentication and authorization.

Summary
Interceptors provide the Struts 2 framework with both power and flexibility. Developers
may add additional interceptors (either ones provided by Struts 2 or ones they create) to
the stack of interceptors executed when an Action class is called.

Navjot Singh – 9625544280 7827675929


97

Unit Testing

 Introduction
 Setup
 Writing A Unit Test
 Test Validation Should Pass
 Test Validation Should Fail
 Summary

The example code for this tutorial, unit-testing, is available at struts-examples

Introduction
Struts 2 supports running unit tests of methods in the Struts Action class with the Struts
2 JUnit plugin. The JUnit plugin allows you to test methods of an Action class from
within the Struts 2 framework. The Struts Servlet -filter and interceptors fire just as if
your application was running on a Servlet container.

The Struts 2 user mailing list is an excellent place to get help. If you are having a
problem getting the tutorial example applications to work search the Struts 2 mailing list.
If you don’t find an answer to your problem, post a question on the mailing list.

Setup
The Struts 2 JUnit plugin jar file must be on your application’s class path. In the
example application (see info above) the pom.xml includes a dependency for
the struts2-junit-plugin. There are numerous transitive dependencies, including to
JUnit and the Spring framework.

Writing A Unit Test


In the example application, the Register Action class includes using the validate
method. This method is automatically executed by the Struts 2 framework prior to the
execute method. Additionally, this method needs the values from the user’s input on the
form to already have been provided to the instance fields of the Action class (this work
is done by another Struts 2 interceptor). So it would be difficult to test the validate
method without the overall Struts 2 framework running.

To use the Struts 2 plugin to ensure the Strut 2 framework runs as part of the test, you
need to have your JUnit test class extend StrutsTestCase (see RegisterTest class in the
example application).

Note that the Struts 2 JUnit plugin can be used to design unit tests of other Action class
methods such as the input method and also to test methods of a custom interceptor you
add to the interceptor stack. Also in this example, the test is for validation performed in

Navjot Singh – 9625544280 7827675929


98

the validate method . But the same type of test would work if the validation was done
using XML file validation.

To test the validate method we want Struts to call the Struts action that will cause the
Action class’s validate and execute methods to be run. In the example application this
action is register.

struts.xml

<action name="register" class="org.apache.struts.register.action.Register" method="ex


ecute">
<result name="success">/thankyou.jsp</result>
<result name="input">/register.jsp</result>
</action>

Remember the validate method will be called automatically by the framework before
calling the execute method. If validation fails the Struts framework will return input. If
there are no validation errors then the framework will call the execute method and return
whatever String the execute method returns.

Test Validation Should Pass


For our first test we’ll test that there should be no validation errors. In the normal flow of
this application the user would first enter the form data shown on the register.jsp page.

The input fields for the form have the following name
values: personBean.firstName, personBean.lastName, personBean.email,
and personBean.age. When the user fills out those fields Struts will take the values and
provide them to the appropriate set methods of the personBean object. So as part of the
test I need to simulate the user filling out these form fields. The StrutsTestCase
provides a request object (of type MockHttpServletRequest) that I can use to set these
values in the request scope.

Navjot Singh – 9625544280 7827675929


99

testExecuteValidationPasses method from RegisterTest class

@Test
public void testExecuteValidationPasses() throws Exception {
request.setParameter("personBean.firstName", "Bruce");
request.setParameter("personBean.lastName", "Phillips");
request.setParameter("personBean.email", "bphillips@ku.edu");
request.setParameter("personBean.age", "19");

ActionProxy actionProxy = getActionProxy("/register.action");


Register action = (Register) actionProxy.getAction() ;

assertNotNull("The action is null but should not be.", action);

String result = actionProxy.execute();

assertEquals("The execute method did not return " + ActionSupport.SUCCESS + " but
should have.", ActionSupport.SUCCESS, result);
}

The first statements in the test method use the request object to set the values of any
request parameters. These simulate the values the user would enter into the form fields.
Note how the first argument to setParameter is the same as the value of the name
attribute in the Struts textfield tag in the register.jsp page.

In this test I’m providing good data for each form field as I want to ensure my validation
doesn’t register an error if the user provides correct information.

I then call the getActionProxy method with the argument of ―/register.action‖ and then
the getAction method to get a reference to the Struts action class for this test. This will
ensure that the Struts 2 JUnit plugin will know which Action class should be used–the
class associated with the register action in the struts.xml. In this case that class is the
Register class.

The assertNotNull test ensures that argument to getActionProxy reference an Action


class identified in struts.xml. It’s a way of checking that you’ve correctly setup struts.xml
for this action.

After that I can call actionProxy.execute(). This causes the Struts 2 framework to go
through its normal process of Servlet filter and interceptors for the action identified by
the actionProxy (in this case that is the register.action). The validate method of class
Navjot Singh – 9625544280 7827675929
100

Register will get called and if it doesn’t create any field or action errors then Struts 2 will
call the execute method. In this example, the execute method should return success.

So in the next statement, I check that success was returned.

Test Validation Should Fail


To test that validation should fail, I just need to have a test method that doesn’t provide
input for a form field. For example, in the validate method of the Register Action class, is
a test to ensure the user has entered some information for the personBean.firstName
input field. In the test method I would just not use the request object to set a parameter
for that field.

testExecuteValidationFailsMissingFirstName method from RegisterTest class

@Test
public void testExecuteValidationFailsMissingFirstName() throws Exception {
//request.setParameter("personBean.firstName", "Bruce");
request.setParameter("personBean.lastName", "Phillips");
request.setParameter("personBean.email", "bphillips@ku.edu");
request.setParameter("personBean.age", "19");

ActionProxy actionProxy = getActionProxy("/register.action");


Register action = (Register) actionProxy.getAction() ;

assertNotNull("The action is null but should not be.", action);

String result = actionProxy.execute();

assertEquals("The execute method did not return " + ActionSupport.INPUT + " but s
hould have.", ActionSupport.INPUT, result);

In the last assertEquals statement my test checks that the Struts 2 framework
returned input as that is what the Struts 2 framework will return if the validation adds a
field or action error.

Summary

Navjot Singh – 9625544280 7827675929


101

There is much more you can do with the Struts 2 JUnit plugin to help you test the
methods of your Action class in conjunction with the Struts 2 framework. If your Struts 2
application uses Spring to inject dependencies into the Action class then the Struts 2
JUnit Plugin has a StrutsSpringTestCase that your test class should extend. Please
read Testing Actions to learn more.

Navjot Singh – 9625544280 7827675929


102

HTTP Session

 Introduction
 SessionAware Interface
 Using the HTTP Session Object In The Action Class
 Accessing HTTP Session Objects In The View
 Best Practices When Using SessionAware
 Summary

The example code for this tutorial, http-session, is available at struts-examples.

Introduction
Your Struts 2 application may need to access the HTTP session object. Struts 2
provides an interface, SessionAware, that your Action class should implement to obtain
a reference to the HTTP session object.

The Struts 2 user mailing list is an excellent place to get help. If you are having a
problem getting the tutorial example applications to work search the Struts 2 mailing list.
If you don’t find an answer to your problem, post a question on the mailing list.

SessionAware Interface
The SessionAware interface has one method, setSession, that your Action class will
need to override. In the example application (see above), the HelloWorldAction class
implements the SessionAware interface and includes this code:

HelloWorldAction.java setSession Method

private Map<String, Object> userSession ;

public void setSession(Map<String, Object> session) {


userSession = session ;
}

The Struts 2 framework has an interceptor that will inject the HTTP session object into
the Action class by calling the setSession method.

Using the HTTP Session Object In The Action Class


The example application keeps track of how many times the user clicks on a Hello link
or submits the hello form. It stores this count in the HTTP session object in the
increaseHelloCount method.

Navjot Singh – 9625544280 7827675929


103

HelloWorldAction.java increaseHelloCount Method

private void increaseHelloCount() {


Integer helloCount = (Integer) userSession.get(HELLO_COUNT);

if (helloCount == null ) {
helloCount = 1;
} else {
helloCount++;
}

userSession.put(HELLO_COUNT, helloCount);
}

When the increaseHelloCount method is called from within the execute method, the
userSession object is a reference to the HTTP session object injected by the Struts 2
framework. So any objects stored in the HTTP session can be retrieved using the
userSession object and any objects stored in the userSession object will be stored in
the HTTP session object.

Accessing HTTP Session Objects In The View


Struts 2 provides an easy way to get an object stored in the HTTP session from within
the view page. In the example application is HelloWorld.jsp with this markup:

HelloWorld.jsp Get helloCount Value From HTTP Session

<p>I've said hello to you <s:property value="#session.helloCount" /> times!</p>

The s:property tag’s value attribute has a value of #session.helloCount. The ―#‖
before the word session tells the Struts framework to look in the session scope for a key
of ―helloCount‖ (which is the value of the String constant HELLO_COUNT referenced in
method increaseHelloCount). Struts will get the object mapped to helloCount key and
then call that object’s toString method to determine what to display in the view page.

Best Practices When Using SessionAware


Using SessionAware does introduce a potential security vulnerability that you should
mitigate by also following these practices in the Action class that implements the
SessionAware interface.

Navjot Singh – 9625544280 7827675929


104

1. Do not have a public Map<String, Object> getSession method in the Action class. You
only need a public void setSession method to implement the SessionAware interface.
2. Also have the Action class implement the ParameterNameAware interface and override
its acceptableParameterName method:

HelloWorldAction.java acceptableParameterName Method

public boolean acceptableParameterName(String parameterName) {


boolean allowedParameterName = true ;

if ( parameterName.contains("session") || parameterName.contains("request") ) {
allowedParameterName = false ;
}

return allowedParameterName;
}

This method will be called by the Struts 2 framework for each parameter in the request
scope. By returning false if the parameter name contains ―session‖ we are telling the
Struts 2 framework to ignore that parameter. This will prevent a malicious user from
trying to hack the HTTP session object.

Instead of having each action that implements SessionAware also implement the
ParameterNameAware interface you can tell t he params interceptor to exclude specific
request attributes for all actions in a package. In struts.xml configure the struts-
default set of interceptors as follows:

struts.xml configure params interceptor

<package name="basicstruts2" extends="struts-default">


<interceptors>
<interceptor-stack name="appDefault">

<interceptor-ref name="defaultStack">

<param name="exception.logEnabled">true</param>
<param name="exception.logLevel">ERROR</param>
<param name="params.excludeParams">dojo..*,^struts..*,^session..*,^re
quest..*,^application..*,^servlet(Request|Response)..*,parameters...*</param>
</interceptor-ref>
</interceptor-stack>

Navjot Singh – 9625544280 7827675929


105

</interceptors>

<default-interceptor-ref name="appDefault" />


...
</package>

The above code will ensure that every action in the ―basicstruts2‖ package that
implements the SessionAware interface will exclude from processing parameters that
starts with the strings provided in the params.excludeParams node.

The example project includes both methods for mitigating the SessionAware security
vulnerability.

Note the same issue exists if you implement the ServletRequestAware interface, which
is why the above method returns false if the parameter name contains “request”.

Summary
When your Action class needs to access the HTTP session object implement the
SessionAware interface and override the setSession method. Be sure to also
implement the ParameterNameAware interface and override
the acceptableParameterName method to mitigate a potential security vulnerability. If you
have multiple actions that implement SessionAware then consider modifying the params
interceptor’s excludeParams value as part of your Struts 2 package setup.

Navjot Singh – 9625544280 7827675929


106

Preparable Interface

 Introduction
 Preparable Interface
 Example Application
 Summary

The example code for this tutorial, preparable-interface, is available at struts-


examples.

Introduction
Often the data used to populate a form control is dynamically generated, perhaps from a
database. When the user submits the form, the Struts 2 validation interceptor attempts
to validate the user’s form input. If validation fails the Struts 2 framework returns the
value input but the input action is not re-executed. Rather the view associated with
the input result is rendered to the user. Usually this view is the page that displayed the
original form.

This work-flow can cause a problem if one or more of the form fields or some other data
displayed depends on a dynamic look-up that that is accomplished in the Action class’s
input method. Since the Action class’s input method is not re-executed when validation
fails, the view page may no longer have access to the correct information to create the
form or other display information.

The Struts 2 user mailing list is an excellent place to get help. If you are having a
problem getting the tutorial example applications to work search the Struts 2 mailing list.
If you don’t find an answer to your problem, post a question on the mailing list.

Preparable Interface
Struts 2 provides the Preparable interface to overcome this problem. An Action class
that implements this interface must override the prepare method. The prepare method
will always be called by the Struts 2 framework’s prepare interceptor whenever any
method is called for the Action class and also when validation fails before the view is
rendered.

In the prepare method you should put any statements that must be executed no matter
what other Action class method will be called and also statements that should be
executed if validation fails. Usually statements in the prepare method set the value for
Action class instance fields that will be used to populate form controls and get the
values that will be used to set the initial form field values.

In addition to automatically running the prepare method the prepare interceptor will also
call a method named prepare<ActionMethodName>. For example, define a prepare
method and a prepareInput method in the Action class that implements Preparable.

Navjot Singh – 9625544280 7827675929


107

When the Struts 2 framework calls the input method, the prepare interceptor will call the
prepareInput and the prepare methods before calling the input method.

Example Application
If you examine class EditAction in the example application (see above) you’ll see that it
implements the Preparable interface. In the prepare method is this code:

EditAction.java prepare Method

carModelsAvailable = carModelsService.getCarModels();

setPersonBean(editService.getPerson());

The above statements get the car model values used to populate the car model check
boxes displayed in the form and also get the information about the Person object being
edited.

When you run the example application, look in the log to see when the prepare method
is called in relation to the input and execute methods. Running the example application
and examining the log should help you understand the impact of implementing
the Preparable interface and the prepare method.

Summary
When your application requires specific statements to be executed no matter which
method of the Action class is called or when validation fails, you should implement the
Preparable interface and override the prepare method.

Navjot Singh – 9625544280 7827675929


108

Exclude Parameters

 Introduction
 Processing Request Parameters
 Excluding Request Parameters From Struts 2 Processing
 Example Application
 Summary

The example code for this tutorial, exclude-parameters, is available at struts-


examples.

Introduction
When Struts development mode is set to true (also see Debugging Struts) the
framework writes many informative messages to the log file. These messages include
ones that indicate whether or not a specific parameter will be handled by the parameter
interceptor and made available to the Action class. These log messages can be helpful
in clearly identifying parameters that you do not want the parameter interceptor to
process for security or other reasons. This article discusses how to exclude parameters
from being handled by the parameter interceptor.

The Struts 2 user mailing list is an excellent place to get help. If you are having a
problem getting the tutorial example applications to work search the Struts 2 mailing list.
If you don’t find an answer to your problem, post a question on the mailing list.

Processing Request Parameters


Most request parameters are by default processed by the parameter interceptor and
Struts 2 will attempt to modify the state of those Action class fields that match up to a
parameter name by calling a corresponding public set method. For example if the
request includes a parameter of lastName with a value of Phillips, Struts 2 will try to call
a public method with a signature of setLastName(String lastName). However, there may
be request parameters that you do not want Struts 2 to try to set the value of in the
Action class.

Consider this code which creates a form:

Struts 2 Form Tags

<s:form action="save" method="post">


<s:textfield key="personBean.firstName" />
<s:textfield key="personBean.lastName" />
<s:textfield key="personBean.email" />
<s:textfield key="personBean.phoneNumber" />

Navjot Singh – 9625544280 7827675929


109

<s:select key="personBean.sport" list="sports" />


<s:radio key="personBean.gender" list="genders" />
<s:select key="personBean.residency" list="states" listKey="stateAbbr" listValue=
"stateName" />
<s:checkbox key="personBean.over21" />
<s:checkboxlist key="personBean.carModels" list="carModelsAvailable" />
<s:submit key="submit" />
</s:form>

The s:submit tag will create a submit button with a name of submit. Since the Action
class probably doesn’t have a setSubmit(String name) method you will see the
following log messages (only if Struts development mode is set to true):

Log Messages

Dec 31, 2012 3:43:53 PM


com.opensymphony.xwork2.util.logging.commons.CommonsLogger warn
WARNING: Parameter [submit] is not on the excludeParams list of patterns and will be
appended to action!

Dec 31, 2012 3:43:53 PM com.opensymphony.xwork2.util.logging.commons.CommonsLogger er


ror
SEVERE: Developer Notification (set struts.devMode to false to disable this message):
Unexpected Exception caught setting 'submit' on 'class org.apache.struts.edit.action.
EditAction: Error setting expression 'submit' with value ['Save Changes', ]

Excluding Request Parameters From Struts 2 Processing


If you’re not familiar with setting up a custom interceptor stack for your Struts 2
application review Introducing Interceptors.

To exclude specific parameters from being processed by the Struts 2 framework you
need to add those parameter names to the list of excluded parameters. One way to do
this is by adding those parameter names to the collection of excludedParams for the
Parameters interceptor. You can do this by modifying the Parameters interceptor in
setting up the stack of interceptors used by your Struts 2 application. For example:

Setup Interceptor Stack To Exclude submit Parameter

<interceptors>

Navjot Singh – 9625544280 7827675929


110

<interceptor-stack name="appDefault">
<interceptor-ref name="defaultStack">
<param name="exception.logEnabled">true</param>
<param name="exception.logLevel">ERROR</param>
<param name="params.excludeParams">dojo..*,^struts..*,^session..*,^reques
t..*,^application..*,^servlet(Request|Response)..*,parameters...*,submit</param>
</interceptor-ref>
</interceptor-stack>
</interceptors>

<default-interceptor-ref name="appDefault" />

The value of node <param name="params.excludeParams"> is a comma-delimited list of


regular expressions or simple Strings that identify request parameters that should NOT
be processed by the Parameters interceptor. To exclude the submit parameter (which is
the name of the submit button in the form code above), I just added submit to the list.

See the Basic Stack of Interceptors described here to view the initial set of parameter
names/regular expressions to exclude. Be sure to copy over the list of parameters
already being excluded and then add your own parameters to the end separated by
commas.

Example Application
Download the example application, exclude-params that demonstrates excluding a
request parameter. See the project’s README.txt file for how to build and run the
application.

To see the log messages written when not excluding the submit parameter remove
the ,submit from the list of excluded parameter values in the struts.xml file. Then rebuild
and redeploy the application and view the console when running the application.

Summary
It’s a nice feature of the Struts 2 framework that it logs during development which
request parameters will and will not be processed. During development of a Struts 2
web application it’s a good practice to review these log messages to determine if there
are any parameters that the framework should not process. For those parameters the
Struts 2 framework should not process add the parameter name (or a regular
expression that can be used to identify multiple parameter names) to the comma-
delimited list that is the value for the <param name="params.excludeParams"> node.

Navjot Singh – 9625544280 7827675929


111

Navjot Singh – 9625544280 7827675929

You might also like