Struts2
Struts2
By Ian Roughley
24,262 Downloads ยท Refcard 20 of 151 (see them all)
Download
FREE PDF
The Essential Struts2 Cheat Sheet
Struts 2
About Struts2
Struts2 is the next generation of model-view-controller web application frameworks. It aims at providing increased productivity through reduced XML configuration, smart conventions, and a modular and loosely-coupled architecture. This refcard refers to Struts2 version 2.0.x.
Configuring the Web Application
To configure Struts2, a filter needs to be configured in the applications web.xml file:
<web-app>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>action2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
Actions
Actions are the basic building blocks of Struts:
public class UserAction {
private int age;
private UserService service;
public int getAge() { return age; }
public void setAge( int age ) { this.age = age; }
public void setUserService( UserService service ) {
this.service = service;
}
public String execute() throws Exception {
service.updateAge(age);
return "success";
}
}
Features of a Struts2 action are:
- An action doesn't need to extend classes or implement interfaces (it's a POJO)
- Use getters and setter to access data in your view and transfer data to and from the action
- Data conversion is done for you by Struts2 (all basic type conversion is available, and you can define your own more complex conversions)
- Pluggable dependency injection is used for services (injecting a Spring Framework-managed bean is as simple as placing a setter on the action with a name that matches the bean's id in the Spring configuration)
- The method providing the logic is called
executeby convention,but it could be called anything,as long as it returns a String and has no parameters (it can also throwException)

Even though an action isn't required to extend another class, it sometimes makes sense. The class ActionSupport is one such class, providing default implementations for validation support, internationalization, etc. so you don't have to.
Configuring Actions
The struts.xml file (accessed via the classpath) provides configuration for Struts2.
<struts>
<constant name="struts.devMode" value="true" />
<package name="test" extends="struts-default"
namespace="/tests" >
<default-interceptor-ref name="basicStack" />
<global-results>
<result name="error" type="dispatcher">
/error.jsp</result>
</global-results>
<global-exception-mappings>
<exception-mapping
exception="java.lang.Exception" result="error" />
</global-exception-mappings>
<default-action-ref name="testMe" />
<action name="updateTest"
method="update"class="com.fdar.s2.MyAction" >
<result name="success" type="dispatcher">/WEB-INF
/jsp/found.jsp</result>
<interceptor-ref name="altStack" />
<exception-mapping
exception="java.lang.Exception"
result="exception" />
<param name="version">2.0.9</param>
</action>
</package>
<include file="struts-module1.xml" />
</struts>

Many of the configuration options are now available as annotations, but not all of them. So it's important to know how to use the struts. xml configuration file.
| Tag Name | Description |
|---|---|
| constant | Changes the value of a configuration property.
|
| package(*) | Provides a way to hierarchically split an application into smaller
units using the URL path namespace.
|
| defaultinterceptor- ref | The interceptors to apply to all actions in the package by default
|
| global-results | Contains a list of result tags (see result tag definition below in this table), that can be referred to by any action in the package (or extending packages) |
| globalexceptionmappings | Contains a list of exception-mapping tags (see exceptionmapping
definition below in this table) to apply to all actions
in the package by default. |
| exceptionmapping (*) | Maps an exception to the result that should be rendered when
the exception is thrown (requires the exception interceptor).
|
| default-actionref | The action to invoke when the URL doesn't match any configured.
|
| action | Describes an action that can be invoked
|
| result | Provides the view options for the result being returned from the
action classes logic method (more than one result is allowed).
|
| interceptor-ref | The interceptors to apply to this action (can use more than one)
|
| param | Allows parameters to be assigned to the action from
configuration files.
|
| include | Includes another configuration file, allowing a large application
to have multiple configuration files.
|
Table 1. struts.xml Configuration Elements
(*) Some attributes have been omitted because they have limited usage, see http://struts.apache.org/2.x/docs/configuration-elements.html for the complete list of configuration attributes available.
For a complete list of configuration properties that can be modified, take a look at http://struts.apache.org/2.x/docs/strutsproperties.html.
Action Annotations
The annotations currently available to actions are listed in Table 2.
| Annotation Name | Description |
|---|---|
| @Namespace | The value is the name of the namespace to use for the action |
| @ParentPackage | The value is the name of the package that the action will inherit from |
| @Results | Used when more than one @Result annotation is configured for
the action.
|
| @Result | Defines the results for an action.
|
Table 2. Action Annotations
When using action-based annotation, there is additional configuration required in web.xml:
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.
FilterDispatcher</filter-class>
<init-param>
<param-name>actionPackages</param-name>
<param-value>com.fdar.apress.s2.actions</param-value>
</init-param>
</filter>
Validation Annotations

To activate annotation-based validation for an action, the class must first be annotated with @Validation. This allows Struts2 to further interrogate only those classes that are known to have validation annotations.
Each of the validations in Table 3 are method level validations, and can be applied to setters or the execute method. As well as their individual attributes, every annotation has the following common attributes:
- message: the message to display to the user
- key (not required): an i18n key from a language specific resource
- shortCircuit (not required): whether to abort other validations if this one fails
Additionally, validators may have the following (annotated in Table 3 as applicable):
- fieldName (not required): specifies the field being acted upon
- type:
Validator.FIELDorValidator.SIMPLE(defaults toValidatorType.FIELD)
| Annotation Name | Description |
|---|---|
| @ConversationErrorFieldValidator (a)(b) | Validates that there are no conversion errors for a field. |
| @DateRangeFieldValidator (a)(b) | Validates that a date falls between a range.
|
| @DoubleRangeFieldValidator (a)(b) | Validates that a double falls between a range.
|
| @EmailValidator (a)(b) | Validates that the email has a valid format. |
| @ExpressionValidator | Validates that an expression evaluates to true.
|
| @FieldExpressionValidator (a) | Validates that a field expression evaluates to true.
|
| IntRangeFieldValidator (a)(b) | Validates that an int falls between a range.
|
| @RequiredFieldValidator (a)(b) | Validates that the field is not null. |
| @RegexFieldValidator (a)(b) | Validates that a string field matches a regular
expression.
|
| @RequiredStringValidator (a)(b) | Validates that the field is not empty (i.e. not null and length > 0) |
| @StringLengthFieldValidator (a)(b) | Validates that a String is of a certain length.
|
| @UrlValidator (a)(b) | Validates that the field has a valid URL format |
| @VisitorFieldValidator (a) | Steps into action properties to continue validation.
This keeps validation for models separate and
re-useable across multiple actions.
|
| @CustomValidator (a)(b) | Used to specify a custom validator. In addition,
an array of @ValidationParameter annotations
can be used to pass parameter to the custom
validator. Custom validators extend the ValidatorSupport
or FieldValidatorSupport class.
|
Table 3. Validation Annotations
Updated documentation on the validators can be found at: http://struts.apache.org/2.x/docs/annotations.html.
The @Validations validator allows you to specify multiple validators
on the execute() method. It has the following parameters:
| Parameter | Description |
|---|---|
| requiredFields | a list of RequiredFieldValidators |
| customValidators | a list of CustomValidators |
| conversionErrorFields | a list of ConversionErrorFieldValidators |
| dateRangeFields | a list of DateRangeFieldValidators |
| emails | a list of EmailValidators |
| fieldExpressions | a list of FieldExpressionValidators |
| intRangeFields | a list of IntRangeFieldValidators |
| requiredStrings | a list of RequiredStringValidators |
| stringLengthFields | a list of StringLengthFieldValidators |
| urls | a list of UrlValidators |
| visitorFields | a list of VisitorFieldValidators |
| regexFields | a list of RegexFieldValidator |
| expressions | a list of ExpressionValidator |
@Validations(
requiredFields = {
@RequiredFieldValidator(
fieldname="userName",
message="Username is required")},
emails = {
@EmailValidator(fieldName="emailAddress",
message="Email address is required")}
)
Conversion Annotations
Similar to validation annotations, when using conversion annotations you must add the class-level @Conversion annotation to the class.
Once this is complete, conversion annotations from Table 4 can be used. These annotations can be applied at the method or property level.
| Annotation Name | Description |
|---|---|
| @TypeConversion | Provides custom conversion for a property or method.
Custom converters extend the StrutsTypeConverter class.
|
Table 4. Conversion Annotations

There are more conversion annotations available, although with generics they are mostly unused. If you're interested, the full list can be found at http://struts.apache.org/2.x/docs/annotations.html.
Result Types
As well as JSP templates, a Struts2 action can render a variety of other options. Each of those available are listed in Table 5.
| Result Type Name | Description |
|---|---|
| Chain Result (*) ActionChainResult.class | Chains one action to another action.
|
| Dispatcher Result ServletDispatcherResult. class | Renders a JSP template.
|
| Freemarker Result (*) FreemarkerResult.class | Renders a Freemarker template.
|
| HttpHeader Result HttpHeaderResult.class | Returns HTTP headers back to the client.
|
| Redirect Result ServletRedirectResult. class | Performs a URL redirect rather than rendering a
template.
|
| Redirect Action Result ServletActionRedirectResult. class | Performs a URL redirect to another Struts2 action.
|
| Velocity Result VelocityResult.class | Renders a Velocity template.
|
| Stream Result (*) StreamResult.class | Streams raw data back to the client.
|
| XSL Result XSLTResult.class | Renders XML by serializing attributes of the action, which
may be parsed through an XSL template.
|
Table 5. Available Result Types

It's not just information from the configuration file that can be used in the result configuration. Expressions and values from the Value Stack can be accessed by placing the expression with the "${" and "}" characters. (i.e. <result>/user/${user. name}</result>).
(*) Some have additional less commonly used parameters. These parameters can be found at http://struts.apache.org/2.x/docs/result-types.html.
The online documentation for Result Types can be found at http://struts.apache.org/2.x/docs/result-types.html.
Interceptors
Interceptors play a large role in providing core framework features in Struts2. Table 6 provides a list of all the interceptors available in Struts2.
(a) denotes those interceptors implementing MethodFilterInterceptor. These interceptors have the following additional parameters:
- excludeMethods: method names to be excluded from interceptor processing
- includeMethods: method names to be included in interceptor processing
| Name/ Configuration Value | Description/Attributes |
|---|---|
| Alias Interceptor alias | Allows parameters in the request to be set on the action
under a different name.
|
| Chaining Interceptor chain | Works with the chain result to copy data from one action
to another.
|
| Checkbox Interceptor checkbox | Looks for a hidden identification field that specifies the
original value of the checkbox. Sets the value of checkbox
elements that aren't submitted.
|
| Cookie Interceptor cookie | Sets values in the Value Stack based on the cookie name
and value-name and value must match for value to be set.
|
| Conversation Error Interceptor conversionError | Sets the conversion errors from the ActionContext into the Action's field errors. |
| Create Session Interceptor createSession | Creates a HttpSession. |
| Execute and Wait Interceptor execAndWait | Starts a long-running action in the background on a separate
thread, while preventing the HTTP request from timing out.
While still in progress, a "wait" result is returned and rendered
for the user (i.e. for an updating progress meter).
|
| Exception Interceptor exception | Allows exception to be handled declaratively
(via configuration).
|
| File Upload Interceptor fileUpload | Allows the multi-part uploading of files. Three setters are
required on the action for each property (the property being
the name of the HTML form element)-{property}: the actual
File, {property}ContentType: the files content type, and
{property}FileName: the name of the file uploaded
|
| Internationalization Interceptor i18n | Allows the setting and switching of user locales.
|
| Logger Interceptor logger | Logs the start and end of the action's execution (logged at the INFO level). |
| Message Store Interceptor store | Stores the action's ValidationAware messages, errors and
field errors into HTTP Session so they can be
accessed after the current HTTP request.
|
| Model Driven Interceptor modelDriven | Places the model (exposed via implementing the the Model- Driven interface on actions) from the action into the Value Stack above the action. |
| Scoped Model Driven Interceptor scopedModelDriven | Retrieves the model (specified by the ScopedModelDriven
interface) before an action executes and stores the model
after execution.
|
| Parameters Interceptor (a) params | This interceptor sets all HTTP parameters onto the
Value Stack. Actions that want to programmatically
define acceptable parameters can implement
ParameterNameAware interface.
|
| Prepare Interceptor (a) prepare | Calls a method for pre-execute logic for classes implementing
the Preparable interface. The method called is either
prepare{methodName}, where {methodName} is usually
execute, or a generic prepare method.
|
| Scope Interceptor scope | Sets action properties from the HTTP session before an
action is executed, and stores them back into the HTTP
session after execution.
|
| Servlet Configuration Interceptor servletConfig | Allows the action to access HTTP information via interfaces. The interfaces that this interceptor supports are: ServletContextAware, ServletRequestAware, ServletResponseAware, ParameterAware, RequestAware, SessionAware, ApplicationAware and PrincipalAware. |
| Static Parameters Interceptor staticParams | Populates the action with the static parameters defined in the action configuration. If the action implements Parameterizable, a map of the static parameters will also be passed directly to the action. |
| Roles Interceptor roles | The action is invoked only if the user has the necessary
role (supplied via the HttpServletRequest).
|
| Timer Interceptor timer | Logs the execution time of the request (in milliseconds).
|
| Token Interceptor (a) token | Ensures that only one request per token (supplied via the token tag) is processed,prevents double submitting of forms. |
| Token Session Interceptor (a) tokenSession | Builds off of the Token Interceptor, providing advanced logic for handling invalid tokens (providing intelligent fail-over in the event of multiple requests using the same session). |
| Validation Interceptor (a) validation | Runs the validations for the action. |
| Workflow Interceptor (a) workflow | Redirects user to an alternative result when validation
errors are present (does not perform validation).
|
| Parameter Filter Interceptor (not pre-configured) | Blocks parameters from entering the Value Stack and
being assigned to the action.
|
| Profiling Interceptor profiling | Enables simple profiling (to the logger) when developer
mode is enabled.
|
Table 6. Available Interceptors,
The online documentation for interceptors can be found at http://struts.apache.org/2.x/docs/interceptors.html.
Interceptors are configured in struts.xml within the package tag. For single interceptors, the interceptor tag is used specifying a unique (across individual interceptors and interceptor stacks) name and the implementing class. To configure interceptor stacks, the interceptor-stack tag is used; listing the interceptor's using the interceptor-ref tag.
<interceptors>
<interceptor name="breadcrumb"
class="com.fdar.BreadCrumbInterceptor" />
<interceptor-stack name="appStack">
<interceptor-ref name="basicStack" />
<interceptor-ref name="breadcrumb" />
</interceptor-stack>
</interceptors>

It's important not only to have the correct interceptors but ensure that they are executed in the correct order. So make sure your interceptor stacks are defined in the order you want the interceptors executed!
The parameters for interceptors can be configured in two ways.
Parameters can be added using the param tag when configuring
the interceptor:
<interceptor-ref name="validation">
<param name="excludeMethods">input,back,cancel,
browse</param>
</interceptor-ref>
The other option is within an actions, configuration, by
specifying the param tag inside the interceptor-ref tag. In this
case, the interceptor name prepends the parameter being set
on the interceptor:
<action name="testMe"
class="com.fdar.apress.s2.MyAction">
<interceptor-ref name="defaultStack">
<param name="validation.excludeMethods">
prepare,findById</param>
</interceptor-ref>
</action>
In addition to the methods that need to be implemented in the Interceptor interface, interceptors can provide lifecycle callbacks. The callbacks methods are denoted by the annotations in Table 7.
| Annotation Name | Description |
|---|---|
| @After | Denotes methods on the interceptor to execute after the execute()
method is invoked.
|
| @Before | Denotes methods on the interceptor to execute before the
execute() method is invoked.
|
| @BeforeResult | Denotes methods on the interceptor to execute before the result
is rendered.
|
Table 7. Interception Annotations


