struts2.0 reference cards

Embed Size (px)

Citation preview

  • 7/28/2019 struts2.0 reference cards

    1/6

    DZone, Inc. | www.dzone.com

    20

    CONTENTS INCLUDE:

    n Confguring the Web Application

    n Actions

    n Confguring Actions

    n Result Types

    n Interceptors

    n

    Hot Tips and more...

    Struts2 is the next generation o model-view-controller web

    application rameworks. It aims at providing increased productivitythrough reduced XML confguration, smart conventions, and a

    modular and loosely-coupled architecture. This recard reers toStruts2 version 2.0.x.

    To confgure Struts2, a flter needs to be confgured in theapplications web.xml fle:

    struts2

    org.apache.struts2.dispatcher.FilterDispatcher

    struts2

    /*

    Actions are the basic building blocks o Struts:

    publicclassUserAction{

    privateintage;

    privateUserServiceservice;

    publicintgetAge(){returnage;}

    publicvoidsetAge(intage){this.age=age;}

    publicvoidsetUserService(UserServiceservice){

    this.service=service;

    }

    publicStringexecute()throwsException{ service.updateAge(age);

    return"success";

    }

    }

    Features of a Struts2 action are:

    n An action doesnt need to extend classes or implement

    interaces (its a POJO)

    n Use getters and setter to access data in your view and

    transer data to and rom the action

    n Data conversion is done or you by Struts2 (all basic type

    conversion is available, and you can defne your own more

    complex conversions)

    The struts.xml fle (accessed via the classpath) provides

    confguration or Struts2.

    /error.jsp

    Actions, continued n Pluggable dependency injection is used or services

    (injecting a Spring Framework-managed bean is as simp

    as placing a setter on the action with a name that matche

    the beans id in the Spring confguration)

    n The method providing the logic is called execute by

    conventionbut it could be called anythingas long

    as it returns a String and has no parameters (it can also

    throw Exception )

    ABOUT STRUTS2

    CONFIGURING THE WEB APPLICATION

    ACTIONS

    CONFIGURING ACTIONS

    S

    truts2

    www.dzon

    e.com

    GetMoreRefcardz!Vi

    sitrefcardz.com

    n Authoritative contentn Designed for developersn Written by top expertsn Latest tools & technologiesn Hot tips & examplesn Bonus content onlinen New issue every 1-2 weeks

    Subscribe Now for FREE!Refcardz.com

    Get More Refcardz(Theyre free!)

    Struts2By Ian Roughle

    Even though an action isnt required to extendanother class, it sometimes makes sense. Theclass ActionSupport is one such class, providingdefault implementations for validation support,

    internationalization, etc. so you dont have to.

    HotTip

    http://www.dzone.com/http://www.dzone.com/http://www.dzone.com/http://www.dzone.com/http://www.dzone.com/http://www.dzone.com/http://www.dzone.com/http://www.dzone.com/http://www.dzone.com/http://www.dzone.com/http://www.dzone.com/http://www.dzone.com/http://www.dzone.com/http://www.dzone.com/http://www.refcardz.com/http://www.refcardz.com/http://www.refcardz.com/http://www.refcardz.com/http://www.refcardz.com/http://www.refcardz.com/http://www.refcardz.com/http://www.refcardz.com/http://www.refcardz.com/http://www.refcardz.com/http://www.refcardz.com/http://www.refcardz.com/http://www.refcardz.com/http://www.refcardz.com/http://www.refcardz.com/http://www.refcardz.com/http://www.refcardz.com/http://www.refcardz.com/http://www.refcardz.com/http://www.refcardz.com/http://www.refcardz.com/http://www.refcardz.com/http://www.dzone.com/http://www.refcardz.com/http://www.dzone.com/
  • 7/28/2019 struts2.0 reference cards

    2/6

    Struts22

    DZone, Inc. | www.dzone.com

    tech facts at your fingertips

    Conguring Actions, continued

    /WEB-INF

    /jsp/found.jsp

    2.0.9

    Action AnnotationsThe annotations currently available to actions are listed in Table 2.

    When using action-based annotation, there is additional

    confguration required in web.xml:

    struts2

    org.apache.struts2.dispatcher.

    FilterDispatcher

    actionPackagescom.fdar.apress.s2.actions

    Validation Annotations

    Each o the validations in Table 3 are method level validations,

    and can be applied to setters or the execute method. As wellas their individual attributes, every annotation has the ollowing

    common attributes:

    n message: the message to display to the user n key (not required): an i18n key rom a language specifc

    resource

    n shortCircuit (not required): whether to abort other

    validations i this one ails

    Additionally, validators may have the ollowing (annotated in

    Table 3 as applicable):

    a. eldName (not required): specifes the feld being

    acted upon

    (*) Some attributes have been omitted because they have

    limited usage, see http://struts.apache.org/2.x/docs/

    confguration-elements.html or the complete list o confguration

    attributes available.

    For a complete list o confguration properties that can be

    modifed, take a look at http://struts.apache.org/2.x/docs/

    strutsproperties.html.

    Table 1. struts.xml Confguration Elements

    Table 2. Action Annotations

    Tag Name Description

    constant Changes the value of a conguration property.nnamethe name o the property or the value to changenvaluethe new value to assign

    package(*) Provides a way to hierarchically split an application into smaller

    units using the URL path namespace.nnamea unique name (across all packages)nextendsthe package to extend (this package)nnamespacethe unique URL path namespace to access the

    actions in this package

    default-

    interceptor-ref

    The interceptors to apply to all actions in the package by defaultnnamethe interceptor or interceptor stack to use

    global-results Contains a list of result tags (see result tag denition below in

    this table), that can be referred to by any action in the package

    (or extending packages)

    global-

    exception-mappings

    Contains a list ofexception-mapping tags (see exception-

    mapping denition below in this table) to apply to all actionsin the package by default.

    exception-

    mapping (*)

    Maps an exception to the result that should be rendered when

    the exception is thrown (requires the exception interceptor).nexceptionthe package and class o the exceptionnresultthe result to orward the user to when the exception is

    encountered

    default-action-

    ref

    The action to invoke when the URL doesn't match any congured.nnamethe action name

    action Describes an act ion that can be invokednnamethe name o the action (".action" is added as an

    extension when used in the URL)nmethod(not required)the method o the class to invoke

    (deaults to "execute")nclassthe 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).nname (not required)the String value returned rom the action

    logic to match (deaults to "success")ntype (not required)the result type to use to render the result

    (deaults to "dispatcher")

    The value within the tags provides the template name to render

    interceptor-ref The interceptors to apply to this action (can use more than one)nnamethe name o the interceptor or interceptor stack

    param Allows parameters to be ass igned to the act ion f rom

    conguration les.nnamethe name o the parameter being assigned

    The value within the tags provides the value to assignmay contain

    OGNL (denoted as ${OGNLExpression} )

    include Includes another conguration le, allowing a large application

    to have multiple conguration les.nlethe name o the fle to include

    Many of the configuration options are nowavailable as annotations, but not all of them.So its important to know how to use the struts.xml configuration file.

    HotTip

    To activate annotation-based validation for anaction, the class must rst be annotated with@Validation. This al lows Struts2 to furtherinterrogate only those classes that are known

    to have validation annotations.

    Note

    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 congured forthe action.

    @Results({@Result(),

    @Result()})

    @Result Denes the results for an action.

    nnamethe result rom the action to match (deaults to success)

    ntypethe result type class to use (i.e. JSP rendering result type)

    nvaluethe value or the result type (i.e. the JSP to render)

    nparams (not required)additional parameters to pass to the

    result type@Result(name="success"

    type=ServletActionRedirectResult.class,value="selectLocation",

    params={"method","input"})

    http://www.dzone.com/http://www.refcardz.com/http://www.refcardz.com/http://struts.apache.org/2.x/docs/configuration-elements.htmlhttp://struts.apache.org/2.x/docs/configuration-elements.htmlhttp://struts.apache.org/2.x/docs/strutsproperties.htmlhttp://struts.apache.org/2.x/docs/strutsproperties.htmlhttp://struts.apache.org/2.x/docs/strutsproperties.htmlhttp://struts.apache.org/2.x/docs/strutsproperties.htmlhttp://struts.apache.org/2.x/docs/configuration-elements.htmlhttp://struts.apache.org/2.x/docs/configuration-elements.htmlhttp://www.refcardz.com/http://www.dzone.com/
  • 7/28/2019 struts2.0 reference cards

    3/6

    3

    DZone, Inc. | www.dzone.com

    Struts2tech facts at your fingertips

    Validation Annotations, continued

    b. type:Validator.FIELD or Validator.SIMPLE (deaults

    to ValidatorType.FIELD)

    @Validations(

    requiredFields={

    @RequiredFieldValidator(

    eldname="userName",

    message="Usernameisrequired")},

    emails={

    @EmailValidator(eldName="emailAddress",

    message="Emailaddressisrequired")}

    )

    Conversion AnnotationsSimilar to validation annotations, when using conversion

    annotations you must add the class-level @Conversion

    annotation to the class.

    Once this is complete, conversion annotations rom Table4 can be used. These annotations can be applied at the

    method or property level.

    Updated documentation on the validators can be ound at:

    http://struts.apache.org/2.x/docs/annotations.html .

    The@Validations validator allows you to speciy multiple validators

    on the execute() method. It has the ollowing parameters:

    Table 3.Validation Annotations

    Table 4. Conversion Annotations

    Annotation Name Description

    @ConversationErrorFieldValidator(a)(b)

    Validates that there are no conversion errorsfor a eld.

    @DateRangeFieldValidator (a)(b) Validates that a date falls between a range.nmin (not required)the minimum valid daten

    max (not required)the maximum valid date@DoubleRangeFieldValidator(

    message="Pleaseenteradatethisyear",

    key="validate.thisYear",

    min="2008/01/01",

    max="2008/12/31")

    @DoubleRangeFieldValidator(a)(b)

    Validates that a double falls between a range.nminInclusive (not required)the inclusive

    minimum valid datenmaxInclusive (not required)the inclusive

    maximum valid datenminExclusive (not required)the exclusive

    minimum valid datenmaxExclusive (not required)the exclusive

    maximum valid date

    @DateRangeFieldValidator(

    message="Pleaseenteradatethisyear",

    key="validate.thisYear",

    minInclusive="2008/01/01",

    maxInclusive="2008/12/31")

    @EmailVal idator (a) (b) Validates that the email has a valid format.

    @Express ionValidator Validates that an express ion evaluates to true.nexpressionthe OGNL expression to evaluate

    @ExpressionValidator(

    message="Pleaseconrmpassword",

    key="conrm.password",

    shortCircuit=true,

    expression=

    "password.equals(conrmPassword)")

    @FieldExpressionValidator (a) Validates that a eld expression evaluates to true.nexpressionthe OGNL expression to evaluate

    IntRangeFieldValidator (a)(b) Validates that an int falls between a range.nmin (not required)the minimum valid datenmax (not required)the maximum valid date

    @RequiredFieldValidator (a)(b) Validates that the eld is not null.

    @RegexFieldValidator (a)(b) Validates that a string eld matches a regularexpression.nexpressionthe regular expression to evaluate

    @RequiredStringValidator (a)(b) Validates that the eld is not empty (i.e. notnull and length > 0)

    @StringLengthFieldValidator (a)(b) Validates that a String is of a certain length.ntrim (not required)removes white space paddingnminLength (not required)the minimum length

    the String must benmaxLength (not required)the maximum length

    the String must be

    @Ur lValidator (a)(b) Validates that the eld has a valid URL format

    @VisitorFieldValidator (a) Steps into action properties to continue validation.This keeps validation for models separate andre-useable across multiple actions.ncontext (not required)the validation context.

    Multiple contexts allow or dierent validationrules in dierent circumstances (deaults toaction context)

    nappendPrefx (not required)whether the propertyname (o the action) should be pre-pendedto the feld name. i.e. user.name vs. name

    (deaults to true).@VisitorFieldValidator(message="ErrorvalidatingUser",key="user.error",shortCircuit=true,context="model",appendPrex=true)

    @CustomValidator (a)(b) Used to specify a custom val idator. In addition,an array of @ValidationParameter annotationscan be used to pass parameter to the customvalidator. Custom validators extend the Valida-torSupport or FieldValidatorSupport class.

    @CustomValidator(type="myUserValidator",eldName="user",parameters={@ValidationParameter(name="source",value="admin")})

    Parameter Description

    requiredFields a list o RequiredFieldValidators

    customValidators a list o CustomValidators

    conversionErrorFields a list o ConversionErrorFieldValidators

    dateRangeFields a list o DateRangeFieldValidators

    emails a list o EmailValidators

    eldExpressions a list o FieldExpressionValidators

    intRangeFields a list o IntRangeFieldValidators

    requiredStrings a list o RequiredStringValidators

    stringLengthFields a list o StringLengthFieldValidators

    urls a list o UrlValidators

    visitorFields a list o VisitorFieldValidators

    regexFields a list o RegexFieldValidator

    expressions a list o ExpressionValidator

    Annotation Name Description

    @TypeConversion Provides custom conversion for a property or method.Custom converters extend the StrutsTypeConverterclass.nkey (not required)the property or key name (deaults to

    property name)ntype (not required)determines the scope o the conversion: ConversionType.APPLICATION or ConversionType.CLASS

    (deaults to ConversionType.CLASS )nrule (not required)the conversion rule:ConversionRule.PROPERTY,ConversionRule.MAP,

    ConversionRule.KEY,ConversionRule.KEY_PROPERTY,

    ConversionRule.ELEMENT,ConversionRule.CREATE_IF_NULL

    (deaults to ConversionRule.PROPERTY )nconverter (converter or value required)the class name o

    the converternvalue (converter or value required)the value to set when using ConversionRule.KEY_PROPERTY

    @TypeConversion(

    type=ConversionType.APPLICATION,

    property="java.util.Date",

    converter=

    "com.opensymphony.xwork2.util.XWorkBasic-Converter")

    There are more conversion an notations avail-able, although with generics they are mostlyunused. If youre interested, the full list canbe found at http://struts.apache.org/2.x/docs/annotations.html.

    HotTip

    http://www.dzone.com/http://www.refcardz.com/http://www.refcardz.com/http://struts.apache.org/2.x/docs/annotations.htmlhttp://struts.apache.org/2.x/docs/annotations.htmlhttp://struts.apache.org/2.x/docs/annotations.htmlhttp://struts.apache.org/2.x/docs/annotations.htmlhttp://struts.apache.org/2.x/docs/annotations.htmlhttp://struts.apache.org/2.x/docs/annotations.htmlhttp://www.refcardz.com/http://www.dzone.com/
  • 7/28/2019 struts2.0 reference cards

    4/6

    4

    DZone, Inc. | www.dzone.com

    Struts2tech facts at your fingertips

    Result Types, continued

    As well as JSP templates, a Struts2 action can render a variety o

    other options. Each o those available are listed in Table 5.

    (*) Some have additional less commonly used parameters.

    These parameters can be ound at http://struts.apache.

    org/2.x/docs/result-types.html.

    The online documentation or Result Types can be ound at

    http://struts.apache.org/2.x/docs/result-types.html.

    RESULT TYPES

    Table 5. Available Result Types, continued

    Table 5. Available Result Types Table 6. Available Interceptors

    Its not just information from the congurationle that can be used in the result conguration.Expressions and val ues from the Value Stackcan be accessed by placing the expression with

    the "${" and "}" characters. (i.e. /user/${user.name}).

    HotTip

    Result Type Name Description

    Chain Result (*)ActionChainResult.class

    Chains one action to another action.nactionName (deault)the action to invoke nextnnamespace (not required)the namespace o the action

    being chained to (deaults to current namespace)nmethod (not required)the method on the action to

    execute (deaults to execute)

    listAction

    /user

    Dispatcher ResultServletDispatcherResult.class

    Renders a JSP template.nlocation (deault)the template to rendernparse (not required)whether to parse OGNL

    expressions (true by deault)

    user.jsp

    or (using the deaults)

    user.jsp

    Freemarker Result (*)FreemarkerResult.class

    Renders a Freemarker template.nlocation (deault)the template to render

    nparse (not required)whether to parse OGNLexpressions (true by deault)

    user.ftl

    HttpHeader ResultHttpHeaderResult.class

    Returns HTTP headers back to the client.nstatusthe HTTP response status code to returnnparse (not required)whether to parse OGNL

    expressions (true by deault)nheaders (not required)header values to returnnerror (not required)the error code to returnnerrorMessage (not required)error message to return

    (i error is set)

    401

    ${username}

    /deleteUser

    Redirect Result

    ServletRedirectResult.class

    Performs a URL redirect rather than rendering a

    template.nlocation (deault)the URL to redirect to

    nparse (not required)whether to parse OGNL

    expressions (true by deault)

    viewUser.jsp

    false

    Redirect Action ResultServletActionRedirectRe-sult.class

    Performs a URL redirect to another Struts2 action.nactionName (deault)the action to redirect tonnamespace (not required)the namespace o the action

    being redirected to (deault to current namespace)

    dashboard

    /secure

    Velocity ResultVelocityResult.class

    Renders a Velocity template.nlocation (deault)the template to rendern

    parse (not required)whether to parse OGNLexpressions (true by deault)

    user.vm

    Stream Result (*)StreamResult.class

    Streams raw data back to the client.ncontentType (not required)the mime-type o the

    response (deaults to text/plain)ncontentLength (not required)the stream length in bytesninputName (not required)the name o the InputStream

    to return to the client (deaults to inputStream)nbuerSize (not required)the buer size when copying

    rom input to output (deault 1024)

    image/jpeg

    imageStream

    Result Type Name Description

    XSL ResultXSLTResult.class

    Renders XML by serializing attributes of the action, whichmay be parsed through an XSL template.nlocation (deault)the template to rendernparse (not required)whether to parse OGNL expressions

    (true by deault)nmatchingPattern (not required)a pattern to match the

    desired elementsnexcludingPattern (not required)a pattern to eliminate

    unwanted elementsuser.xslt^/result/[^/*]$

    Interceptors play a large role in providing core ramework eatures

    in Struts2. Table 6 provides a list o all the interceptors available

    in Struts2.

    (a) denotes those interceptors implementing

    MethodFilterInterceptor . These interceptors have the ollowing

    additional parameters:

    n excludeMethods: method names to be excluded rom

    interceptor processing

    n includeMethods: method names to be included in

    interceptor processing

    INTERCEPTORS

    Name/Conguration Value

    Description/Attributes

    Alias Interceptoralias

    Allows parameters in the request to be set on the actionunder a different name.naliasesKey (not required)the name o the action parameter

    that contains the name-to-alias map (deaults to aliases).

    #{'action':'alias'}

    Chaining Interceptorchain

    Works with the chain result to copy data from one actionto another.nexcludes (not required)the list o parameter names to

    exclude rom copying (all others will be included).nincludes (not required)the list o parameter names to

    include when copying (all others will be excluded).

    Checkbox Interceptorcheckbox

    Looks for a hidden identication eld that species theoriginal value of the checkbox. Sets the value of checkboxelements that arent submitted.nsetUncheckedValue (not required)the value to set as the

    unchecked value (deaults to alse)

    Cookie Interceptorcookie

    Sets values in the Value Stack based on the cookie nameand valuename and value must match for value to be set.ncookiesNamecomma separated list o cookie names to be

    injected into the Value Stack (all cookies can be specifed with

    an asterisk).ncookiesValuecomma separated list o cookie values to

    match (all cookies names can be specifed by using anasterisk or the value)

    http://www.dzone.com/http://www.refcardz.com/http://www.refcardz.com/http://struts.apache.org/2.x/docs/result-types.htmlhttp://struts.apache.org/2.x/docs/result-types.htmlhttp://struts.apache.org/2.x/docs/result-types.htmlhttp://struts.apache.org/2.x/docs/result-types.htmlhttp://struts.apache.org/2.x/docs/result-types.htmlhttp://struts.apache.org/2.x/docs/result-types.htmlhttp://www.refcardz.com/http://www.dzone.com/
  • 7/28/2019 struts2.0 reference cards

    5/6

    5

    DZone, Inc. | www.dzone.com

    Struts2tech facts at your fingertips

    Interceptors, continued

    Table 6. Available Interceptors, continued

    Table 6. Available Interceptors, continued

    Name/Conguration Value

    Description/Attributes

    Conversation ErrorInterceptorconversionError

    Sets the conversion errors from the ActionContext into theActions eld errors.

    Create SessionInterceptorcreateSession

    Creates a HttpSession.

    Execute and WaitInterceptorexecAndWait

    Starts a long-running action in the background on a separatethread, while preventing the HTTP request from timing out.While still in progress, a wait result is returned and renderedfor the user (i.e. for an updating progress meter).nthreadPriority (not required)the priority to assign the

    processing thread (deault Thread.NORM_PRIORITY)ndelay (not required)an initial delay beore the wait page

    is displayedndelaySleepInterval (not required)how long to wait

    between wait page rereshing (only used with delay, deaultis 100 milliseconds)

    Exception Interceptorexception

    Allows exception to be handled declaratively(via conguration).nlogEnabled (not required)whether to log exceptionsnlogLevel (not required)the logging level to use

    (deault is debug)nlogCategory (not required)the logging category to use

    (deault is com.opensymphony.xwork2.interceptor.Exception

    MappingInterceptor)

    FileUpload InterceptorfleUpload

    Allows the multi-part uploading of les. Three setters arerequired on the action for each property (the property beingthe name of the HTML form element){property}: the actualFile, {property}ContentType: the les content type, and

    {property}FileName: the name of the le uploadednmaximumSize (not required)the maximum size in bytes or

    the fle (deault to ~2MB)nallowedTypes (not required)a comma separated list o

    allowed content types, i.e. text/html (deaults to allow all types)

    InternationalizationInterceptori18n

    Allows the setting and switching of user locales.nparameterName (not required)the name o the HTTP

    request parameter that can switch the locale (deault isrequest_locale)

    nattributeName (not required)the name o thesession key to store the selected locale (deault isWW_TRANS_I18N_LOCALE)

    Logger Interceptorlogger

    Logs the start and end of the actions execution (logged atthe INFO level).

    Message StoreInterceptorstore

    Stores the act ions ValidationAware messages, errors andeld errors into HTTP Session so they can beaccessed after the current HTTP request.nallowRequestParameterSwitch (not required)enables

    the request parameter that can switch the operationmode o the interceptor

    nrequestParameterSwitch (not required)the requestparameter that will indicate what mode this interceptor is in.

    noperationMode (not required) the operation mode,'STORE': stores messages; 'RETRIEVE': retrieves storedmessages, or 'NONE': do nothing (deaults to 'NONE')

    Model DrivenInterceptormodelDriven

    Places the model (exposed via implementing the ModelDriveninterface on actions) from the action into the Value Stackabove the action.

    Scoped Model DrivenInterceptorscopedModelDriven

    Retrieves the model (specied by the ScopedModelDriveninterface) before an action executes and stores the modelafter execution.nclassName (not required)the model class name

    (deaults to the model class name)nname (not required)the key to store the model under

    (deaults to the model class name).nscope (not required)the scope to store the model under

    (deaults to 'request' but can also be 'session')

    Parameters Intercep-tor (a)params

    This interceptor sets all HTTP parameters onto theValue Stack. Actions that want to programmaticallydene acceptable parameters can implementParameterNameAware interface.nordered (not required)set to true i you want the top-

    down property setter behavior

    Prepare Interceptor (a)prepare

    Calls a method for pre-execute logic for c lasses implement-ing the Preparable interface. The method called is eitherprepare{methodName}, where {methodName} is usuallyexecute, or a generic prepare method.nalwaysInvokePrepare (not required)determines whether

    the prepare method will always be invoked (deaults to true)

    Name/Conguration Value

    Description/Attributes

    Scope Interceptorscope

    Sets action properties from the HTTP session before anaction is executed, and stores them back into the HTTPsession after execution.nsession (not required)a comma delimited list o properties

    to be stored in HTTP session scopenapplication (not required)a comma delimited list o

    properties to be stored in HTTP application scopenkey (not required)the key to store the properties under,

    can be CLASS (generates a unique key based on the class

    name), ACTION (generates a unique key based on theaction name), any supplied valuentype (not required)start: all properties are set to the

    actions deault values; end: all properties are removedonce the action is run; anything else keeps deault behavior

    nsessionReset (not required)when set to true all propertiesare reset

    Servlet CongurationInterceptorservletConfg

    Allows the action to access HTTP information viainterfaces. The interfaces that this interceptor supportsare: ServletContextAware, ServletRequestAware,ServletResponseAware, ParameterAware, RequestAware,SessionAware, ApplicationAware and PrincipalAware.

    Static ParametersInterceptorstaticParams

    Populates the action with the static parameters denedin the action conguration. If the action implementsParameterizable, a map of the static parameters will alsobe passed directly to the act ion.

    Roles Interceptorroles

    The action is invoked only if the user has the necessaryrole (supplied via the HttpServletRequest).nallowedRolesroles allowed to access the actionn

    disallowedRolesroles not allowed to access the actionTimer Interceptortimer

    Logs the execution time of the request (in milliseconds).nlogLevel (not required)the logging level to use

    (deault is ino)nlogCategory (not required)the logging category to

    use (deault is com.opensymphony.xwork2.interceptorTimerInterceptor)

    Token Interceptor (a)token

    Ensures that only one request per token (supplied via the to-ken tag) is processedprevents double submitting of forms.

    Token SessionInterceptor (a)tokenSession

    Builds off of the Token Interceptor, providing advancedlogic for handling invalid tokens (providing intelligentfail-over in the event of multiple requests using the samesession).

    Validation Interceptor (a)validation

    Runs the validations for the action.

    Workow Interceptor (a)workow

    Redirects user to an alternative result when validationerrors are present (does not perform validation).ninputResultName (not required)the result to return

    when validation errors exist (deaults to input)

    Parameter FilterInterceptor(not pre-confgured)

    Blocks parameters from entering the Value Stack andbeing assigned to the action.nallowed (not required)a comma delimited list o parameter

    prefxes that are allowednblockeda comma delimited list o parameter prefxes

    that are not allowed to passndeaultBlocki true, all parameters are blocked and only

    those matching the allowed attribute will be allowed topass (deault to alse)

    Proling Interceptorprofling

    Enables simple proling (to the logger) when developermode is enabled.nproflingKeythe key to use to activate profling

    The online documentation or interceptors can be ound at

    http://struts.apache.org/2.x/docs/interceptors.html.

    Interceptors are confgured in struts.xml within the package tag.For single interceptors, the interceptor tag is used speciying a

    unique (across individual interceptors and interceptor stacks) name

    and the implementing class. To confgure interceptor stacks, the

    interceptor-stack tag is used; listing the interceptors using the

    interceptor-ref tag.

    http://www.dzone.com/http://www.refcardz.com/http://www.refcardz.com/http://struts.apache.org/2.x/docs/interceptors.htmlhttp://struts.apache.org/2.x/docs/interceptors.htmlhttp://www.refcardz.com/http://www.dzone.com/
  • 7/28/2019 struts2.0 reference cards

    6/6

    Struts26

    tech facts at your fingertips

    DZone, Inc.

    1251 NW Maynard

    Cary, NC 27513

    888.678.0399

    919.678.0300

    Refcardz Feedback Welcome

    [email protected]

    Sponsorship Opportunities

    [email protected]

    Copyright 2008 DZone, Inc. All rights reserved. No part o this publication may be reproduced, stored in a retrieval system, or transmitted, in any orm or by means electronic, mechanical,

    photocopying, or otherwise, without prior written permission o the publisher. Reerence: Practical Struts2 Web 2.0 Projects, Ian Roughley, APress, November 2007

    Version 1

    ISBN-13: 978-1-934238-17-2

    ISBN-10: 1-934238-17-1

    9 781934 238172

    5 0 7 9 5

    ABOUT THE AUTHOR RECOMMENDED BOOK

    The latest v2 release o Apache Struts takes

    developers capabilities to the next level,

    having integrated Ajax support, the ability to

    easily integration with the Spring ramework,

    and the ability to take ull advantage o

    POJOs.Practical Apache Struts 2 Web 2.0

    Projects shows you how to capitalize upon

    these new eatures to build nextgeneration web applications

    that both enthrall and empower your users.

    BUY NOWbooks.dzone.com/books/struts2

    Ian Roughley

    Ian Roughley is a speaker, author, and consultant. For more than ten

    years he has been helping clients ranging in size rom Fortune 10

    companies to start-ups. Focused on a pragmatic and results-based

    approach, he is a proponent or open source, as well as process and

    quality improvements through agile development techniques.

    PublicationsAuthor oStarting Struts2and Practical Struts2 Web 2.0 Projects; Java editor orInfoQ.com

    Web Site Emailhttp://www.dar.com [email protected]

    Interceptors, continued

    Its important not only to have the correctinterceptors but ensure that they are executed inthe correct order. So make sure your interceptorstacks are defined in the order you want theinterceptors executed!

    HotTip

    The parameters or interceptors can be confgured in two ways.Parameters can be added using the param tag when confguring

    the interceptor:

    input,back,cancel,

    browse

    The other option is within an actions confguration, by

    speciying the param tag inside the interceptor-ref tag. In this

    case, the interceptor name prepends the parameter being set

    on the interceptor:

    prepare,ndById

    In addition to the methods that need to be implemented in the

    Interceptor interace, interceptors can provide liecycle callbacks.

    The callbacks methods are denoted by the annotations in Table 7.

    Table 7. Interception Annotations

    Annotation Name Description

    @After Denotes methods on the interceptor to execute after the execute()method is invoked.npriority (not required)the order to execute @Ater annotations

    @Before Denotes methods on the interceptor to execute before theexecute() method is invoked.npriority (not required)the order to execute @Beore annotations

    @BeforeResult Denotes methods on the interceptor to execute before the resultis rendered.npriority (not required)the order to execute @BeoreResult annotations

    Get More FREE Refcardz.Vis it refcardz.comnow!

    Upcoming Refcardz:

    Core Seam

    Core CSS: Part III

    Hibernate Search

    Equinox

    EMF

    XML

    JSP Expression Language

    ALM Best Practices

    HTML and XHTML

    Available:

    Essential Ruby

    Essential MySQL

    JUnit and EasyMock

    Getting Started with MyEclipse

    Spring Annotations

    Core Java

    Core CSS: Part II

    PHP

    Getting Started with JPA

    JavaServer Faces

    Core CSS: Part I

    Struts2

    Core .NET

    Very Firs t Steps in Flex

    C#

    Groovy

    NetBeans IDE 6.1 Java Editor

    RSS and Atom

    GlassFish Application Server

    Silverlight 2

    Visit refcardz.com or a complete listing o available Recardz.Design Patterns

    Published June 2008

    FREE

    DZone communities deliver over 4 million pages each month to

    more than 1.7 million software developers, architects and decision

    makers. DZone offers something for everyone, including news,

    tutorials, cheatsheets, blogs, feature articles, source code and more.

    DZone is a developers dream, says PC Magazine.

    http://www.refcardz.com/http://www.refcardz.com/http://www.dzone.com/mailto:[email protected]:[email protected]://books.dzone.com/books/struts2http://books.dzone.com/books/struts2http://books.dzone.com/books/struts2http://books.dzone.com/books/struts2http://books.dzone.com/starting-struts2http://books.dzone.com/books/struts2http://books.dzone.com/books/struts2http://www.infoq.com/http://www.infoq.com/http://www.fdar.com/mailto:[email protected]://www.refcardz.com/http://refcardz.dzone.com/refcardz/junit-and-easymockhttp://refcardz.dzone.com/refcardz/spring-annotationshttp://refcardz.dzone.com/refcardz/core-javahttp://refcardz.dzone.com/refcardz/corecss2http://refcardz.dzone.com/refcardz/phphttp://refcardz.dzone.com/refcardz/getting-started-with-jpahttp://refcardz.dzone.com/refcardz/corecss-part1http://refcardz.dzone.com/refcardz/corecss-part1http://refcardz.dzone.com/refcardz/struts2http://refcardz.dzone.com/refcardz/coredotnethttp://refcardz.dzone.com/refcardz/very-first-steps-flexhttp://refcardz.dzone.com/refcardz/csharphttp://refcardz.dzone.com/refcardz/groovyhttp://refcardz.dzone.com/refcardz/netbeanshttp://refcardz.dzone.com/refcardz/rss-and-atomhttp://refcardz.dzone.com/refcardz/glassfish-application-serverhttp://refcardz.dzone.com/refcardz/silverlight2http://refcardz.dzone.com/http://refcardz.dzone.com/http://refcardz.dzone.com/http://refcardz.dzone.com/refcardz/design-patternshttp://refcardz.dzone.com/refcardz/design-patternshttp://refcardz.dzone.com/refcardz/design-patternshttp://refcardz.dzone.com/http://refcardz.dzone.com/refcardz/intellij-ideahttp://refcardz.dzone.com/refcardz/silverlight2http://refcardz.dzone.com/refcardz/glassfish-application-serverhttp://refcardz.dzone.com/refcardz/rss-and-atomhttp://refcardz.dzone.com/refcardz/netbeanshttp://refcardz.dzone.com/refcardz/groovyhttp://refcardz.dzone.com/refcardz/csharphttp://refcardz.dzone.com/refcardz/very-first-steps-flexhttp://refcardz.dzone.com/refcardz/coredotnethttp://refcardz.dzone.com/refcardz/struts2http://refcardz.dzone.com/refcardz/corecss-part1http://refcardz.dzone.com/refcardz/corecss-part1http://refcardz.dzone.com/refcardz/getting-started-with-jpahttp://refcardz.dzone.com/refcardz/phphttp://refcardz.dzone.com/refcardz/corecss2http://refcardz.dzone.com/refcardz/core-javahttp://refcardz.dzone.com/refcardz/spring-annotationshttp://refcardz.dzone.com/refcardz/junit-and-easymockhttp://www.refcardz.com/mailto:[email protected]://www.fdar.com/http://www.infoq.com/http://books.dzone.com/books/struts2http://books.dzone.com/starting-struts2http://books.dzone.com/books/struts2http://books.dzone.com/books/struts2http://books.dzone.com/books/struts2http://books.dzone.com/books/struts2mailto:[email protected]:[email protected]://www.dzone.com/http://www.dzone.com/http://www.refcardz.com/