UiPath Platform: The Backend Engine Powering Your Automation - Session 1
DZONE Struts2 reference card
1. #20
Get More Refcardz! Visit refcardz.com
CONTENTS INCLUDE:
Struts2
n
Configuring the Web Application
n
Actions
n
Configuring Actions
n
Result Types
Interceptors
By Ian Roughley
n
n
Hot Tips and more...
Actions, continued
ABOUT STRUTS2 n Pluggable dependency injection is used for services
Struts2 is the next generation of model-view-controller web (injecting a Spring Framework-managed bean is as simple
application frameworks. It aims at providing increased productivity as placing a setter on the action with a name that matches
through reduced XML configuration, smart conventions, and a the bean’s id in the Spring configuration)
modular and loosely-coupled architecture. This refcard refers to n The method providing the logic is called execute by
Struts2 version 2.0.x. convention—but it could be called anything—as long
as it returns a String and has no parameters (it can also
CONFIGURING THE WEB APPLICATION throw Exception )
To configure Struts2, a filter needs to be configured in the Even though an action isn’t required to extend
applications web.xml file: Hot another class, it sometimes makes sense. The
<web-app> Tip class ActionSupport is one such class, providing
<filter>
default implementations for validation support,
<filter-name>struts2</filter-name>
internationalization, etc. so you don’t have to.
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
CONFIGURING ACTIONS
</filter>
<filter-mapping>
The struts.xml file (accessed via the classpath) provides
<filter-name>struts2</filter-name>
configuration for Struts2.
www.dzone.com
<url-pattern>/*</url-pattern>
<struts>
</filter-mapping>
<constant name="struts.devMode" value="true" />
</web-app>
<package name="test" extends="struts-default"
namespace="/tests" >
ACTIONS
<default-interceptor-ref name="basicStack" />
Actions are the basic building blocks of Struts: <global-results>
<result name="error" type="dispatcher">
public class UserAction {
/error.jsp</result>
private int age;
</global-results>
private UserService service;
<global-exception-mappings>
public int getAge() { return age; }
<exception-mapping
public void setAge( int age ) { this.age = age; }
exception="java.lang.Exception" result="error" />
</global-exception-mappings>
public void setUserService( UserService service ) {
→
this.service = service;
}
Get More Refcardz
public String execute() throws Exception {
(They’re free!)
service.updateAge(age);
return "success";
n Authoritative content
}
}
n Designed for developers
n Written by top experts
Features of a Struts2 action are: n Latest tools & technologies
n An action doesn’t need to extend classes or implement n Hot tips & examples
interfaces (it’s a POJO) n Bonus content online
Use getters and setter to access data in your view and
Struts 2
n
n New issue every 1-2 weeks
transfer data to and from the action
n Data conversion is done for you by Struts2 (all basic type Subscribe Now for FREE!
conversion is available, and you can define your own more Refcardz.com
complex conversions)
DZone, Inc. | www.dzone.com
2. 2
Struts2
tech facts at your fingertips
Configuring Actions, continued (*) Some attributes have been omitted because they have
limited usage, see http://struts.apache.org/2.x/docs/
<default-action-ref name="testMe" />
configuration-elements.html for the complete list of configuration
<action name="updateTest" attributes available.
method="update"class="com.fdar.s2.MyAction" >
<result name="success" type="dispatcher">/WEB-INF For a complete list of configuration properties that can be
/jsp/found.jsp</result> modified, take a look at http://struts.apache.org/2.x/docs/
<interceptor-ref name="altStack" /> strutsproperties.html.
<exception-mapping
exception="java.lang.Exception" Action Annotations
result="exception" /> The annotations currently available to actions are listed in Table 2.
<param name="version">2.0.9</param>
</action> Annotation Name Description
@Namespace The value is the name of the namespace to use for the action
</package>
@ParentPackage The value is the name of the package that the action will inherit from
<include file="struts-module1.xml" />
@Results Used when more than one @Result annotation is configured for
</struts> the action.
@Results({
@Result(…),
Many of the configuration options are now @Result(…)
})
Hot available as annotations, but not all of them.
@Result Defines the results for an action.
Tip So it’s important to know how to use the struts. n name—the result from the action to match (defaults to “success”)
xml configuration file. n type—the result type class to use (i.e. JSP rendering result type)
n value—the value for the result type (i.e. the JSP to render)
n params (not required)—additional parameters to pass to the
result type
Tag Name Description
@Result(
constant Changes the value of a configuration property. name="success"
n name—the name of the property for the value to change
type= ServletActionRedirectResult.class,
value="selectLocation",
n value—the new value to assign
params={"method","input"})
package(*) Provides a way to hierarchically split an application into smaller
units using the URL path namespace. Table 2. Action Annotations
n name—a unique name (across all packages)
n extends—the package to extend (this package)
When using action-based annotation, there is additional
n namespace—the unique URL path namespace to access the
configuration required in web.xml:
actions in this package
<filter>
default- The interceptors to apply to all actions in the package by default
interceptor-ref name—the interceptor or interceptor stack to use
n
<filter-name>struts2</filter-name>
<filter-class>
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 org.apache.struts2.dispatcher.
(or extending packages) FilterDispatcher</filter-class>
global- Contains a list of exception-mapping tags (see exception- <init-param>
exception- mapping definition below in this table) to apply to all actions <param-name>actionPackages</param-name>
mappings in the package by default. <param-value>com.fdar.apress.s2.actions</param-value>
exception- Maps an exception to the result that should be rendered when </init-param>
mapping (*) the exception is thrown (requires the exception interceptor). </filter>
n exception—the package and class of the exception
n result—the result to forward the user to when the exception is
Validation Annotations
encountered
default-action- The action to invoke when the URL doesn't match any configured.
ref name—the action name
n
To activate annotation-based validation for an
action Describes an action that can be invoked
n name—the name of the action (".action" is added as an
Note action, the class must first be annotated with
@Validation. This allows Struts2 to further
extension when used in the URL)
n method (not required)—the method of the class to invoke interrogate only those classes that are known
(defaults to "execute") to have validation annotations.
n class—the class that provides the action logic
result Provides the view options for the result being returned from the
action classes logic method (more than one result is allowed). Each of the validations in Table 3 are method level validations,
n name (not required)—the String value returned from the action
and can be applied to setters or the execute method. As well
logic to match (defaults to "success")
n type (not required)—the result type to use to render the result
as their individual attributes, every annotation has the following
(defaults to "dispatcher") common attributes:
The value within the tags provides the template name to render
n message: the message to display to the user
interceptor-ref The interceptors to apply to this action (can use more than one)
n name—the name of the interceptor or interceptor stack
n key (not required): an i18n key from a language specific
resource
param Allows parameters to be assigned to the action from
configuration files. n shortCircuit (not required): whether to abort other
n name—the name of the parameter being assigned
validations if this one fails
The value within the tags provides the value to assign—may contain
OGNL (denoted as ${OGNLExpression}) Additionally, validators may have the following (annotated in
include Includes another configuration file, allowing a large application Table 3 as applicable):
to have multiple configuration files.
n file—the name of the file to include a. fieldName (not required): specifies the field being
Table 1. struts.xml Configuration Elements acted upon
→
DZone, Inc. | www.dzone.com
3. 3
Struts2
tech facts at your fingertips
Validation Annotations, continued Updated documentation on the validators can be found at:
b. type: Validator.FIELD or Validator.SIMPLE (defaults http://struts.apache.org/2.x/docs/annotations.html.
to ValidatorType.FIELD) The @Validations validator allows you to specify multiple validators
Annotation Name Description on the execute() method. It has the following parameters:
@ConversationErrorFieldValidator Validates that there are no conversion errors
(a)(b) for a field. Parameter Description
@DateRangeFieldValidator (a)(b) Validates that a date falls between a range. requiredFields a list of RequiredFieldValidators
n min (not required)—the minimum valid date
n max (not required)—the maximum valid date
customValidators a list of CustomValidators
@DoubleRangeFieldValidator( conversionErrorFields a list of ConversionErrorFieldValidators
message = "Please enter a date this year",
key = "validate.thisYear", dateRangeFields a list of DateRangeFieldValidators
min = "2008/01/01",
max = "2008/12/31") emails a list of EmailValidators
@DoubleRangeFieldValidator Validates that a double falls between a range. fieldExpressions a list of FieldExpressionValidators
(a)(b) n minInclusive (not required)—the inclusive
minimum valid date intRangeFields a list of IntRangeFieldValidators
n maxInclusive (not required)—the inclusive
maximum valid date requiredStrings a list of RequiredStringValidators
n minExclusive (not required)—the exclusive
stringLengthFields a list of StringLengthFieldValidators
minimum valid date
n maxExclusive (not required)—the exclusive urls a list of UrlValidators
maximum valid date
visitorFields a list of VisitorFieldValidators
@DateRangeFieldValidator(
message = "Please enter a date this year",
regexFields a list of RegexFieldValidator
key = "validate.thisYear",
minInclusive = "2008/01/01",
expressions a list of ExpressionValidator
maxInclusive = "2008/12/31")
@EmailValidator (a)(b) Validates that the email has a valid format.
@Validations(
@ExpressionValidator Validates that an expression evaluates to true.
n expression—the OGNL expression to evaluate
requiredFields = {
@ExpressionValidator( @RequiredFieldValidator(
message = "Please confirm password",
key = "confirm.password",
fieldname="userName",
shortCircuit = true, message="Username is required")},
expression =
"password.equals(confirmPassword)" ) emails = {
@FieldExpressionValidator (a) Validates that a field expression evaluates to true. @EmailValidator(fieldName="emailAddress",
expression—the OGNL expression to evaluate
n
message="Email address is required")}
IntRangeFieldValidator (a)(b) Validates that an int falls between a range. )
min (not required)—the minimum valid date
n
max (not required)—the maximum valid date
n
Conversion Annotations
@RequiredFieldValidator (a)(b) Validates that the field is not null. Similar to validation annotations, when using conversion
@RegexFieldValidator (a)(b) Validates that a string field matches a regular annotations you must add the class-level @Conversion
expression.
n expression—the regular expression to evaluate annotation to the class.
@RequiredStringValidator (a)(b) Validates that the field is not empty (i.e. not Once this is complete, conversion annotations from Table
null and length > 0)
4 can be used. These annotations can be applied at the
@StringLengthFieldValidator (a)(b) Validates that a String is of a certain length.
n trim (not required)—removes white space padding method or property level.
n minLength (not required)—the minimum length
the String must be Annotation Name Description
n maxLength (not required)—the maximum length
@TypeConversion Provides custom conversion for a property or method.
the String must be
Custom converters extend the StrutsTypeConverter class.
@UrlValidator (a)(b) Validates that the field has a valid URL format n key (not required)—the property or key name (defaults to
property name)
@VisitorFieldValidator (a) Steps into action properties to continue validation. n type (not required)—determines the scope of the conversion:
This keeps validation for models separate and ConversionType.APPLICATION or ConversionType.CLASS
re-useable across multiple actions. (defaults to ConversionType.CLASS)
n context (not required)—the validation context.
n rule (not required)—the conversion rule:
Multiple contexts allow for different validation ConversionRule.PROPERTY, ConversionRule.MAP,
rules in different circumstances (defaults to ConversionRule.KEY, ConversionRule.KEY_PROPERTY,
action context) ConversionRule.ELEMENT, ConversionRule.CREATE_IF_NULL
n appendPrefix (not required)—whether the property (defaults to ConversionRule.PROPERTY)
name (of the action) should be pre-pended n converter (converter or value required)—the class name of
to the field name. i.e. “user.name” vs. “name” the converter
(defaults to true). n value (converter or value required)—the value to set when using
@VisitorFieldValidator( ConversionRule.KEY_PROPERTY
message = "Error validating User", @TypeConversion(
key = "user.error",
type = ConversionType.APPLICATION,
shortCircuit = true,
property = "java.util.Date",
context = "model",
appendPrefix = true) converter =
"com.opensymphony.xwork2.util.XWorkBasic-Converter")
@CustomValidator (a)(b) Used to specify a custom validator. In addition,
an array of @ValidationParameter annotations Table 4. Conversion Annotations
can be used to pass parameter to the custom
validator. Custom validators extend the Valida-
torSupport or FieldValidatorSupport class.
@CustomValidator( There are more conversion annotations avail-
type ="myUserValidator",
fieldName = "user", Hot able, although with generics they are mostly
parameters = {
@ValidationParameter(
Tip unused. If you’re interested, the full list can
name = "source",
value = "admin" ) }
be found at http://struts.apache.org/2.x/
) docs/annotations.html.
Table 3. Validation Annotations
DZone, Inc. | www.dzone.com
4. 4
Struts2
tech facts at your fingertips
Result Types, continued
RESULT TYPES
Result Type Name Description
As well as JSP templates, a Struts2 action can render a variety of XSL Result Renders XML by serializing attributes of the action, which
XSLTResult.class may be parsed through an XSL template.
other options. Each of those available are listed in Table 5. n location (default)—the template to render
n parse (not required)—whether to parse OGNL expressions
Result Type Name Description (true by default)
n matchingPattern (not required)—a pattern to match the
Chain Result (*) Chains one action to another action. desired elements
ActionChainResult.class n actionName (default)—the action to invoke next n excludingPattern (not required)—a pattern to eliminate
n namespace (not required)—the namespace of the action unwanted elements
being chained to (defaults to current namespace) <result name="success" type="xslt">
n method (not required)—the method on the action to
<param name="location">user.xslt</param>
<param name="matchingPattern">^/result/[^/*]$<param>
execute (defaults to execute) </result>
<result type="chain">
<param name="actionName">listAction</param> Table 5. Available Result Types, continued
<param name="namespace">/user</param>
</result>
Dispatcher Result Renders a JSP template. It’s not just information from the configuration
ServletDispatcherResult.
class
n location (default)—the template to render Hot file that can be used in the result configuration.
n parse (not required)—whether to parse OGNL
expressions (true by default) Tip Expressions and values from the Value Stack
<result name="success" can be accessed by placing the expression with
type="dispatcher">user.jsp</result>
or (using the defaults) the "${" and "}" characters. (i.e. <result>/user/${user.
<result>user.jsp</result> name}</result>).
Freemarker Result (*) Renders a Freemarker template.
FreemarkerResult.class n location (default)—the template to render (*) Some have additional less commonly used parameters.
n parse (not required)—whether to parse OGNL
expressions (true by default) These parameters can be found at http://struts.apache.
<result name="success" org/2.x/docs/result-types.html.
type="freemarker">user.ftl</result>
The online documentation for Result Types can be found at
HttpHeader Result Returns HTTP headers back to the client.
HttpHeaderResult.class n status—the HTTP response status code to return
http://struts.apache.org/2.x/docs/result-types.html.
n parse (not required)—whether to parse OGNL
expressions (true by default)
n headers (not required)—header values to return
INTERCEPTORS
n error (not required)—the error code to return
n errorMessage (not required)—error message to return
Interceptors play a large role in providing core framework features
(if error is set)
<result name="notAuthorized" type="httpheader">
in Struts2. Table 6 provides a list of all the interceptors available
<param name="status">401</param> in Struts2.
<param name="headers.user">${username}</param>
<param name="headers.resource">/deleteUser</param> (a) denotes those interceptors implementing
</result>
MethodFilterInterceptor. These interceptors have the following
Redirect Result Performs a URL redirect rather than rendering a additional parameters:
ServletRedirectResult. template.
class n location (default)—the URL to redirect to
n excludeMethods: method names to be excluded from
n parse (not required)—whether to parse OGNL
interceptor processing
expressions (true by default)
<result name="success" type="redirect">
n includeMethods: method names to be included in
<param name="location">viewUser.jsp</param> interceptor processing
<param name="parse">false</param>
</result>
Name/ Description/Attributes
Redirect Action Result Performs a URL redirect to another Struts2 action. Configuration Value
ServletActionRedirectRe- n actionName (default)—the action to redirect to
Alias Interceptor Allows parameters in the request to be set on the action
sult.class n namespace (not required)—the namespace of the action
alias under a different name.
being redirected to (default to current namespace) aliasesKey (not required)—the name of the action parameter
n
<result type="redirectAction"> that contains the name-to-alias map (defaults to aliases).
<param name="actionName">dashboard</param> <action name="test" class="com.examples.TestAction">
<param name="namespace">/secure</param> <param name="aliases">#{ 'action' : 'alias' }</param>
</result> </action>
Velocity Result Renders a Velocity template. Chaining Interceptor Works with the chain result to copy data from one action
VelocityResult.class n location (default)—the template to render chain to another.
n parse (not required)—whether to parse OGNL n excludes (not required)—the list of parameter names to
expressions (true by default) exclude from copying (all others will be included).
n includes (not required)—the list of parameter names to
<result name="success" type="velocity">
<param name="location">user.vm</param> include when copying (all others will be excluded).
</result>
Checkbox Interceptor Looks for a hidden identification field that specifies the
Stream Result (*) Streams raw data back to the client. checkbox original value of the checkbox. Sets the value of checkbox
elements that aren’t submitted.
StreamResult.class n contentType (not required)—the mime-type of the
n setUncheckedValue (not required)—the value to set as the
response (defaults to text/plain)
unchecked value (defaults to false)
n contentLength (not required)—the stream length in bytes
n inputName (not required)—the name of the InputStream Cookie Interceptor Sets values in the Value Stack based on the cookie name
to return to the client (defaults to inputStream) cookie and value—name and value must match for value to be set.
n bufferSize (not required)—the buffer size when copying n cookiesName—comma separated list of cookie names to be
from input to output (default 1024) injected into the Value Stack (all cookies can be specified with
<result name="success" type="stream"> an asterisk).
n cookiesValue—comma separated list of cookie values to
<param name="contentType">image/jpeg</param>
<param name="inputName">imageStream</param> match (all cookies names can be specified by using an
</result> asterisk for the value)
Table 5. Available Result Types Table 6. Available Interceptors
→
DZone, Inc. | www.dzone.com
5. 5
Struts2
tech facts at your fingertips
Interceptors, continued Name/ Description/Attributes
Configuration Value
Name/ Description/Attributes
Scope Interceptor Sets action properties from the HTTP session before an
Configuration Value
scope action is executed, and stores them back into the HTTP
Conversation Error Sets the conversion errors from the ActionContext into the session after execution.
n session (not required)—a comma delimited list of properties
Interceptor Action’s field errors.
conversionError to be stored in HTTP session scope
n application (not required)—a comma delimited list of
Create Session Creates a HttpSession. properties to be stored in HTTP application scope
n key (not required)—the key to store the properties under,
Interceptor
createSession can be CLASS (generates a unique key based on the class
name), ACTION (generates a unique key based on the
Execute and Wait Starts a long-running action in the background on a separate action name), any supplied value
Interceptor thread, while preventing the HTTP request from timing out. n type (not required)—‘start’: all properties are set to the
execAndWait While still in progress, a “wait” result is returned and rendered actions default values; ‘end’: all properties are removed
for the user (i.e. for an updating progress meter). once the action is run; anything else keeps default behavior
n threadPriority (not required)—the priority to assign the n sessionReset (not required)—when set to true all properties
processing thread (default Thread.NORM_PRIORITY) are reset
n delay (not required)—an initial delay before the wait page
Servlet Configuration Allows the action to access HTTP information via
is displayed
n delaySleepInterval (not required)—how long to wait
Interceptor interfaces. The interfaces that this interceptor supports
servletConfig are: ServletContextAware, ServletRequestAware,
between wait page refreshing (only used with delay, default
ServletResponseAware, ParameterAware, RequestAware,
is 100 milliseconds)
SessionAware, ApplicationAware and PrincipalAware.
Exception Interceptor Allows exception to be handled declaratively Static Parameters Populates the action with the static parameters defined
exception (via configuration). Interceptor in the action configuration. If the action implements
n logEnabled (not required)—whether to log exceptions
staticParams Parameterizable, a map of the static parameters will also
n logLevel (not required)—the logging level to use
be passed directly to the action.
(default is debug)
n logCategory (not required)—the logging category to use
Roles Interceptor The action is invoked only if the user has the necessary
roles role (supplied via the HttpServletRequest).
(default is com.opensymphony.xwork2.interceptor.Exception
n allowedRoles—roles allowed to access the action
MappingInterceptor) n disallowedRoles—roles not allowed to access the action
File Allows the multi-part uploading of files. Three setters are Timer Interceptor Logs the execution time of the request (in milliseconds).
Upload Interceptor required on the action for each property (the property being timer n logLevel (not required)—the logging level to use
fileUpload the name of the HTML form element)—{property}: the actual
(default is info)
File, {property}ContentType: the files content type, and n logCategory (not required)—the logging category to
{property}FileName: the name of the file uploaded
use (default is com.opensymphony.xwork2.interceptor
n maximumSize (not required)—the maximum size in bytes for
TimerInterceptor)
the file (default to ~2MB)
n allowedTypes (not required)—a comma separated list of Token Interceptor (a) Ensures that only one request per token (supplied via the to-
allowed content types, i.e. text/html (defaults to allow all types) token ken tag) is processed—prevents double submitting of forms.
Internationalization Allows the setting and switching of user locales. Token Session Builds off of the Token Interceptor, providing advanced
Interceptor n parameterName (not required)—the name of the HTTP Interceptor (a) logic for handling invalid tokens (providing intelligent
i18n request parameter that can switch the locale (default is tokenSession fail-over in the event of multiple requests using the same
request_locale) session).
n attributeName (not required)—the name of the
Validation Interceptor (a) Runs the validations for the action.
session key to store the selected locale (default is validation
WW_TRANS_I18N_LOCALE)
Workflow Interceptor (a) Redirects user to an alternative result when validation
Logger Interceptor Logs the start and end of the action’s execution (logged at workflow errors are present (does not perform validation).
logger the INFO level). n inputResultName (not required)—the result to return
when validation errors exist (defaults to input)
Message Store Stores the action’s ValidationAware messages, errors and
Interceptor field errors into HTTP Session so they can be Parameter Filter Blocks parameters from entering the Value Stack and
store accessed after the current HTTP request. Interceptor being assigned to the action.
n allowRequestParameterSwitch (not required)—enables (not pre-configured) n allowed (not required)—a comma delimited list of parameter
the request parameter that can switch the operation prefixes that are allowed
mode of the interceptor n blocked—a comma delimited list of parameter prefixes
n requestParameterSwitch (not required)—the request
that are not allowed to pass
parameter that will indicate what mode this interceptor is in. n defaultBlock—if true, all parameters are blocked and only
n operationMode (not required) – the operation mode,
those matching the allowed attribute will be allowed to
'STORE': stores messages; 'RETRIEVE': retrieves stored pass (default to false)
messages, or 'NONE': do nothing (defaults to 'NONE')
Profiling Interceptor Enables simple profiling (to the logger) when developer
Model Driven Places the model (exposed via implementing the ModelDriven profiling mode is enabled.
Interceptor interface on actions) from the action into the Value Stack profilingKey—the key to use to activate profiling
n
modelDriven above the action.
Table 6. Available Interceptors, continued
Scoped Model Driven Retrieves the model (specified by the ScopedModelDriven
Interceptor interface) before an action executes and stores the model
scopedModelDriven after execution. The online documentation for interceptors can be found at
n className (not required)—the model class name
http://struts.apache.org/2.x/docs/interceptors.html.
(defaults to the model class name)
n name (not required)—the key to store the model under Interceptors are configured in struts.xml within the package tag.
(defaults to the model class name). For single interceptors, the interceptor tag is used specifying a
n scope (not required)—the scope to store the model under
(defaults to 'request' but can also be 'session') unique (across individual interceptors and interceptor stacks) name
Parameters Intercep- This interceptor sets all HTTP parameters onto the
and the implementing class. To configure interceptor stacks, the
tor (a) Value Stack. Actions that want to programmatically interceptor-stack tag is used; listing the interceptor’s using the
params define acceptable parameters can implement
ParameterNameAware interface. interceptor-ref tag.
n ordered (not required)—set to true if you want the top-
<interceptors>
down property setter behavior
<interceptor name="breadcrumb"
Prepare Interceptor (a) Calls a method for pre-execute logic for classes implement- class="com.fdar.BreadCrumbInterceptor" />
prepare ing the Preparable interface. The method called is either
prepare{methodName}, where {methodName} is usually <interceptor-stack name="appStack">
execute, or a generic prepare method. <interceptor-ref name="basicStack" />
n alwaysInvokePrepare (not required)—determines whether
<interceptor-ref name="breadcrumb" />
the prepare method will always be invoked (defaults to true)
</interceptor-stack>
Table 6. Available Interceptors, continued </interceptors>
DZone, Inc. | www.dzone.com