Академический Документы
Профессиональный Документы
Культура Документы
com
tech facts at your fingertips
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 The method providing the logic is called execute by
n
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>
<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" />
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)
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)
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)
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
message: the message to display to the user
n
interceptor-ref The interceptors to apply to this action (can use more than one)
n name—the name of the interceptor or interceptor stack
key (not required): an i18n key from a language specific
n
resource
param Allows parameters to be assigned to the action from
configuration files. n shortCircuit (not required): whether to abort other
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
property name)
@VisitorFieldValidator (a) Steps into action properties to continue validation. n type (not required)—determines the scope of the conversion:
@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
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
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
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)
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
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
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
(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>
<param name="excludeMethods">input,back,cancel,
browse</param> @Before Denotes methods on the interceptor to execute before the
execute() method is invoked.
</interceptor-ref> priority (not required)—the order to execute @Before annotations
n
The other option is within an actions’ configuration, by @BeforeResult Denotes methods on the interceptor to execute before the result
specifying the param tag inside the interceptor-ref tag. In this is rendered.
n priority (not required)—the order to execute @BeforeResult annotations
case, the interceptor name prepends the parameter being set
on the interceptor: Table 7. Interception Annotations
Groovy
Dependency Injection in EJB 3
n
n Spring Annotations n
DZone, Inc.
1251 NW Maynard
ISBN-13: 978-1-934238-17-2
Cary, NC 27513
ISBN-10: 1-934238-17-1
50795
888.678.0399
DZone communities deliver over 3.5 million pages per month to 919.678.0300
more than 1.5 million software developers, architects and designers.
Refcardz Feedback Welcome
DZone offers something for every developer, including news, refcardz@dzone.com
$7.95
tutorials, blogs, cheatsheets, feature articles, source code and more. Sponsorship Opportunities 9 781934 238172
“DZone is a developer’s dream,” says PC Magazine. sales@dzone.com
Copyright © 2008 DZone, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, Version 1.0
photocopying, or otherwise, without prior written permission of the publisher. Reference: Practical Struts2 Web 2.0 Projects, Ian Roughley, APress, November 2007