SlideShare una empresa de Scribd logo
1 de 6
Descargar para leer sin conexión
Subscribe Now for FREE! refcardz.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              	    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>action2</filter-name>                                configuration for Struts2.
  www.dzone.com




                                                             <url-pattern>/*</url-pattern>
                                                                                                                               <struts>
                                                          </filter-mapping>
                                                                                                                               <constant name=quot;struts.devModequot; value=quot;truequot; />
                                                      </web-app>
                                                                                                                               <package name=quot;testquot; extends=quot;struts-defaultquot;
                                                                                                                               namespace=quot;/testsquot; >
                                                     ACTIONS
                                                                                                                                    <default-interceptor-ref name=quot;basicStackquot; />

                                                 Actions are the basic building blocks of Struts:                                   <global-results>
                                                                                                                                      <result name=quot;errorquot; type=quot;dispatcherquot;>
                                                      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=quot;java.lang.Exceptionquot; result=quot;errorquot; />
                                                                                                                                    </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 quot;successquot;;                                                                                 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
                                                                                                                                                                                        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=quot;testMequot; />
                                                                                                   configuration-elements.html for the complete list of configuration
   <action name=quot;updateTestquot;                                                                       attributes available.
   method=quot;updatequot;class=quot;com.fdar.s2.MyActionquot; >
     <result name=quot;successquot; type=quot;dispatcherquot;>/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=quot;altStackquot; />                                                           strutsproperties.html.
     <exception-mapping
     exception=quot;java.lang.Exceptionquot;                                                               Action Annotations
     result=quot;exceptionquot; />                                                                         The annotations currently available to actions are listed in Table 2.
     <param name=quot;versionquot;>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=quot;struts-module1.xmlquot; />
                                                                                                       @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=quot;successquot;
                     n		 name—the name of the property for the value to change
                                                                                                                             type= ServletActionRedirectResult.class,
                                                                                                                             value=quot;selectLocationquot;,
                     n		 value—the new value to assign
                                                                                                                             params={quot;methodquot;,quot;inputquot;})
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 (quot;.actionquot; 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 quot;executequot;)                                                         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 quot;successquot;)
                     n		 type (not required)—the result type to use to render the result
                                                                                                   as their individual attributes, every annotation has the following
                         (defaults to quot;dispatcherquot;)                                                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
                                                                                                                                                                                   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 = quot;Please enter a date this yearquot;,
                                         key = quot;validate.thisYearquot;,                              dateRangeFields                        a list of DateRangeFieldValidators
                                         min = quot;2008/01/01quot;,
                                         max = quot;2008/12/31quot;)                                     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 = quot;Please enter a date this yearquot;,
                                                                                                 regexFields                            a list of RegexFieldValidator
                                         key = quot;validate.thisYearquot;,
                                         minInclusive = quot;2008/01/01quot;,
                                                                                                 expressions                            a list of ExpressionValidator
                                         maxInclusive = quot;2008/12/31quot;)

@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 = quot;Please confirm passwordquot;,
                                         key = quot;confirm.passwordquot;,
                                                                                                          fieldname=quot;userNamequot;,
                                         shortCircuit = true,                                             message=quot;Username is requiredquot;)},
                                         expression =
                                         quot;password.equals(confirmPassword)quot; )                         emails = {
@FieldExpressionValidator (a)        Validates that a field expression evaluates to true.               @EmailValidator(fieldName=quot;emailAddressquot;,
                                      expression—the OGNL expression to evaluate
                                     n			
                                                                                                          message=quot;Email address is requiredquot;)}
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 = quot;Error validating Userquot;,                                           @TypeConversion(
                                         key = quot;user.errorquot;,
                                                                                                                        type = ConversionType.APPLICATION,
                                         shortCircuit = true,
                                                                                                                        property = quot;java.util.Datequot;,
                                         context = quot;modelquot;,
                                         appendPrefix = true)                                                           converter =
                                                                                                                        quot;com.opensymphony.xwork2.util.XWorkBasic-Converterquot;)
@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 =quot;myUserValidatorquot;,
                                       fieldName = quot;userquot;,                                                Hot         able, although with generics they are mostly
                                       parameters = {
                                          @ValidationParameter(
                                                                                                          Tip         unused. If you’re interested, the full list can
                                            name = quot;sourcequot;,
                                            value = quot;adminquot; ) }
                                                                                                                      be found at http://struts.apache.org/2.x/
                                     )                                                                                docs/annotations.html.
Table 3. Validation Annotations

                                                                             DZone, Inc.    |   www.dzone.com
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=quot;successquot; type=quot;xsltquot;>
                                  n			method (not required)—the method on the action to
                                                                                                                                  <param name=quot;locationquot;>user.xslt</param>
                                                                                                                                  <param name=quot;matchingPatternquot;>^/result/[^/*]$<param>
                                      execute (defaults to execute)                                                             </result>
                                  <result type=quot;chainquot;>
                                    <param name=quot;actionNamequot;>listAction</param>                      Table 5. Available Result Types, continued
                                    <param name=quot;namespacequot;>/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=quot;successquot;                                                                 can be accessed by placing the expression with
                                      type=quot;dispatcherquot;>user.jsp</result>
                                  or (using the defaults)                                                     the quot;${quot; and quot;}quot; 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=quot;successquot;                                             org/2.x/docs/result-types.html.
                                    type=quot;freemarkerquot;>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=quot;notAuthorizedquot; type=quot;httpheaderquot;>
                                                                                                     in Struts2. Table 6 provides a list of all the interceptors available
                                    <param name=quot;statusquot;>401</param>                                 in Struts2.
                                    <param name=quot;headers.userquot;>${username}</param>
                                    <param name=quot;headers.resourcequot;>/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=quot;successquot; type=quot;redirectquot;>
                                                                                                     	    n   includeMethods: method names to be included in
                                    <param name=quot;locationquot;>viewUser.jsp</param>                               interceptor processing
                                    <param name=quot;parsequot;>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=quot;redirectActionquot;>                                                                   that contains the name-to-alias map (defaults to aliases).
                                    <param name=quot;actionNamequot;>dashboard</param>                                                    <action name=quot;testquot; class=quot;com.examples.TestActionquot;>
                                    <param name=quot;namespacequot;>/secure</param>                                                           <param name=quot;aliasesquot;>#{ '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=quot;successquot; type=quot;velocityquot;>
                                    <param name=quot;locationquot;>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=quot;successquot; type=quot;streamquot;>                                                               an asterisk).
                                                                                                                                  n			cookiesValue—comma separated list of cookie values to
                                    <param name=quot;contentTypequot;>image/jpeg</param>
                                    <param name=quot;inputNamequot;>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
                                                                                                                                                                                                   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 the Model-                      profiling                    mode is enabled.
Interceptor                  Driven interface on actions) from the action into the Value                                                  profilingKey—the key to use to activate profiling
                                                                                                                                         n			


modelDriven                  Stack 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=quot;breadcrumbquot;
Prepare Interceptor (a)      Calls a method for pre-execute logic for classes implement-                         class=quot;com.fdar.BreadCrumbInterceptorquot; />
prepare                      ing the Preparable interface. The method called is either
                             prepare{methodName}, where {methodName} is usually                                  <interceptor-stack name=quot;appStackquot;>
                             execute, or a generic prepare method.                                                  <interceptor-ref name=quot;basicStackquot; />
                             n			alwaysInvokePrepare (not required)—determines whether
                                                                                                                    <interceptor-ref name=quot;breadcrumbquot; />
                                 the prepare method will always be invoked (defaults to true)
                                                                                                                 </interceptor-stack>
Table 6. Available Interceptors, continued                                                                     </interceptors>


                                                                                       DZone, Inc.     |   www.dzone.com
6
                                                                                                                                                                                                                              Struts2
              tech facts at your fingertips




        Interceptors, continued                                                                                                        <action name=quot;testMequot;
                                                                                                                                       class=quot;com.fdar.apress.s2.MyActionquot;>
                                                                                                                                         <interceptor-ref name=quot;defaultStackquot;>
                                It’s important not only to have the correct                                                                 <param name=quot;validation.excludeMethodsquot;>
                Hot             interceptors but ensure that they are executed in                                                           prepare,findById</param>
                Tip             the correct order. So make sure your interceptor                                                         </interceptor-ref>
                                stacks are defined in the order you want the                                                           </action>

                                interceptors executed!                                                                           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.
         The parameters for interceptors can be configured in two ways.
         Parameters can be added using the param tag when configuring                                                              Annotation Name           Description
         the interceptor:                                                                                                          @After                    Denotes methods on the interceptor to execute after the execute()
              <interceptor-ref name=quot;validationquot;>                                                                                                            method is invoked.
                                                                                                                                                              priority (not required)—the order to execute @After annotations
                                                                                                                                                             n			

                <param name=quot;excludeMethodsquot;>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




     AbOUT ThE AUThOr                                                                                                                                    rECOMMENDED bOOK

                              Ian Roughley                                                                                                                                The latest v2 release of Apache Struts takes
                              Ian Roughley is a speaker, author, and consultant. For more than ten                                                                        developers’ capabilities to the next level,
                                                                                                                                                                          having integrated Ajax support, the ability to
                              years he has been helping clients ranging in size from Fortune 10
                                                                                                                                                                          easily integration with the Spring framework,
                              companies to start-ups. Focused on a pragmatic and results-based
                                                                                                                                                                          and the ability to take full advantage of
                              approach, he is a proponent for open source, as well as process and                                                                         POJOs. Practical Apache Struts 2 Web 2.0
                              quality improvements through agile development techniques.                                                                                  Projects shows you how to capitalize upon
                                                                                                                                                         these new features to build next–generation web applications
     Publications                                                                                                                                        that both enthrall and empower your users.
     Author of Starting Struts2 and Practical Struts2 Web 2.0 Projects; Java editor for InfoQ.com

     Web Site                                                       Email                                                                                                                   bUy NOW
     http://www.fdar.com                                            ian@fdar.com                                                                                       books.dzone.com/books/struts2


 Want More? Download Now. Subscribe at refcardz.com
 Upcoming Refcardz:                                       Available:                                                 n   		Silverlight 2
                                                                                                                         		IntelliJ IDEA
     		JPA
                                                                                                                     n


                                                          Published September 2008
                                                                                                                                                                                   frEE
 n



 n   		JSF                                                n   		Core CSS: Part I                                     Published June 2008
                                                                                                                     n   	 jQuerySelectors
     		Agile Methodologies
                                                                                                                         	 Design Patterns
 n
                                                          Published August 2008                                      n


 n   		Core Java                                          n   		Core .NET                                            n   	 Flexible Rails: Flex 3 on Rails 2
     		PHP                                                n   		Very First Steps in Flex
                                                                                                                     Published May 2008
 n



     		Core CSS: Part II                                      	 C#
                                                                                                                         	 Windows PowerShell
                                                          n
 n                                                                                                                   n

                                                              	 Groovy
                                                                                                                         	 Dependency Injection in EJB 3
                                                          n
 n   		Spring Annotations                                                                                            n




 n   		JUnit                                              Published July 2008                                        Published April 2008
                                                          n   		NetBeans IDE 6.1 Java Editor                         n   	 Spring Configuration                                                    GWT Style, Configuration
                                                          n   		RSS and Atom                                         n   	 Getting Started with Eclipse                                                and JSNI Reference
                                                              		GlassFish Application Server                             	 Getting Started with Ajax                                                         Published April 2008
                                                          n                                                          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

Más contenido relacionado

Destacado

Basta chiacchere sulle metriche, un po’ di esempi
Basta chiacchere sulle metriche,  un po’ di esempi Basta chiacchere sulle metriche,  un po’ di esempi
Basta chiacchere sulle metriche, un po’ di esempi matteopanfilo
 
Tom Lazar Using Zope3 Views And Viewlets For Plone 3.0 Product Development
Tom Lazar   Using Zope3 Views And Viewlets For Plone 3.0 Product DevelopmentTom Lazar   Using Zope3 Views And Viewlets For Plone 3.0 Product Development
Tom Lazar Using Zope3 Views And Viewlets For Plone 3.0 Product DevelopmentVincenzo Barone
 
PECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life betterPECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life betterZendCon
 
Adam Peller Interoperable Ajax Tools And Mashups
Adam Peller Interoperable Ajax Tools And MashupsAdam Peller Interoperable Ajax Tools And Mashups
Adam Peller Interoperable Ajax Tools And MashupsAjax Experience 2009
 
Metriche e customer acquisition - Startup Weekend Bari
Metriche e customer acquisition - Startup Weekend BariMetriche e customer acquisition - Startup Weekend Bari
Metriche e customer acquisition - Startup Weekend Barimatteopanfilo
 
KPIs & Metrics - Innlab TN 2013
KPIs & Metrics - Innlab TN 2013KPIs & Metrics - Innlab TN 2013
KPIs & Metrics - Innlab TN 2013matteopanfilo
 
Hype vs. Reality: The AI Explainer
Hype vs. Reality: The AI ExplainerHype vs. Reality: The AI Explainer
Hype vs. Reality: The AI ExplainerLuminary Labs
 

Destacado (10)

Basta chiacchere sulle metriche, un po’ di esempi
Basta chiacchere sulle metriche,  un po’ di esempi Basta chiacchere sulle metriche,  un po’ di esempi
Basta chiacchere sulle metriche, un po’ di esempi
 
Tom Lazar Using Zope3 Views And Viewlets For Plone 3.0 Product Development
Tom Lazar   Using Zope3 Views And Viewlets For Plone 3.0 Product DevelopmentTom Lazar   Using Zope3 Views And Viewlets For Plone 3.0 Product Development
Tom Lazar Using Zope3 Views And Viewlets For Plone 3.0 Product Development
 
PECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life betterPECL Picks - Extensions to make your life better
PECL Picks - Extensions to make your life better
 
Adam Peller Interoperable Ajax Tools And Mashups
Adam Peller Interoperable Ajax Tools And MashupsAdam Peller Interoperable Ajax Tools And Mashups
Adam Peller Interoperable Ajax Tools And Mashups
 
Informix and PHP
Informix and PHPInformix and PHP
Informix and PHP
 
Metriche e customer acquisition - Startup Weekend Bari
Metriche e customer acquisition - Startup Weekend BariMetriche e customer acquisition - Startup Weekend Bari
Metriche e customer acquisition - Startup Weekend Bari
 
Show cooking 1
Show cooking 1Show cooking 1
Show cooking 1
 
Struts Ppt 1
Struts Ppt 1Struts Ppt 1
Struts Ppt 1
 
KPIs & Metrics - Innlab TN 2013
KPIs & Metrics - Innlab TN 2013KPIs & Metrics - Innlab TN 2013
KPIs & Metrics - Innlab TN 2013
 
Hype vs. Reality: The AI Explainer
Hype vs. Reality: The AI ExplainerHype vs. Reality: The AI Explainer
Hype vs. Reality: The AI Explainer
 

Más de reynolds

Three Thing In The Life
Three Thing In The LifeThree Thing In The Life
Three Thing In The Lifereynolds
 
Snake Catchers In Africa
Snake Catchers In AfricaSnake Catchers In Africa
Snake Catchers In Africareynolds
 
Tsunami Before & After
Tsunami Before & AfterTsunami Before & After
Tsunami Before & Afterreynolds
 
America chooses barack obama
America chooses barack obamaAmerica chooses barack obama
America chooses barack obamareynolds
 
Obama Biden
Obama BidenObama Biden
Obama Bidenreynolds
 
Vote For The Barack Obama
Vote For The Barack ObamaVote For The Barack Obama
Vote For The Barack Obamareynolds
 
Barack Obama
Barack ObamaBarack Obama
Barack Obamareynolds
 
Vote For Change
Vote For ChangeVote For Change
Vote For Changereynolds
 
Barack Obama
Barack ObamaBarack Obama
Barack Obamareynolds
 
ObamaShirts
ObamaShirtsObamaShirts
ObamaShirtsreynolds
 
Obama+Presidential+Seal
Obama+Presidential+SealObama+Presidential+Seal
Obama+Presidential+Sealreynolds
 
Barack Obama Phots Gallery
Barack Obama Phots GalleryBarack Obama Phots Gallery
Barack Obama Phots Galleryreynolds
 
Barack Obama
Barack ObamaBarack Obama
Barack Obamareynolds
 
Canstruction
CanstructionCanstruction
Canstructionreynolds
 
Some Of The Beautiful Temples Of The World
Some Of The Beautiful Temples Of The WorldSome Of The Beautiful Temples Of The World
Some Of The Beautiful Temples Of The Worldreynolds
 
Learn to live
Learn to liveLearn to live
Learn to livereynolds
 
MANAGING RISK IN INTERNATIONAL BUSINESS
MANAGING RISK IN INTERNATIONAL BUSINESSMANAGING RISK IN INTERNATIONAL BUSINESS
MANAGING RISK IN INTERNATIONAL BUSINESSreynolds
 
Artistic Airplanes
Artistic AirplanesArtistic Airplanes
Artistic Airplanesreynolds
 
America The Beautiful
America The BeautifulAmerica The Beautiful
America The Beautifulreynolds
 

Más de reynolds (20)

Three Thing In The Life
Three Thing In The LifeThree Thing In The Life
Three Thing In The Life
 
Snake Catchers In Africa
Snake Catchers In AfricaSnake Catchers In Africa
Snake Catchers In Africa
 
Tsunami Before & After
Tsunami Before & AfterTsunami Before & After
Tsunami Before & After
 
America chooses barack obama
America chooses barack obamaAmerica chooses barack obama
America chooses barack obama
 
Obama Biden
Obama BidenObama Biden
Obama Biden
 
Vote For The Barack Obama
Vote For The Barack ObamaVote For The Barack Obama
Vote For The Barack Obama
 
Barack Obama
Barack ObamaBarack Obama
Barack Obama
 
Vote For Change
Vote For ChangeVote For Change
Vote For Change
 
Barack Obama
Barack ObamaBarack Obama
Barack Obama
 
ObamaShirts
ObamaShirtsObamaShirts
ObamaShirts
 
Obama+Presidential+Seal
Obama+Presidential+SealObama+Presidential+Seal
Obama+Presidential+Seal
 
Barack Obama Phots Gallery
Barack Obama Phots GalleryBarack Obama Phots Gallery
Barack Obama Phots Gallery
 
Barack Obama
Barack ObamaBarack Obama
Barack Obama
 
Canstruction
CanstructionCanstruction
Canstruction
 
Some Of The Beautiful Temples Of The World
Some Of The Beautiful Temples Of The WorldSome Of The Beautiful Temples Of The World
Some Of The Beautiful Temples Of The World
 
Learn to live
Learn to liveLearn to live
Learn to live
 
MANAGING RISK IN INTERNATIONAL BUSINESS
MANAGING RISK IN INTERNATIONAL BUSINESSMANAGING RISK IN INTERNATIONAL BUSINESS
MANAGING RISK IN INTERNATIONAL BUSINESS
 
Artistic Airplanes
Artistic AirplanesArtistic Airplanes
Artistic Airplanes
 
America The Beautiful
America The BeautifulAmerica The Beautiful
America The Beautiful
 
Good Life
Good LifeGood Life
Good Life
 

Último

Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 

Último (20)

Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 

Struts2 Online 100

  • 1. Subscribe Now for FREE! refcardz.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 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>action2</filter-name> configuration for Struts2. www.dzone.com <url-pattern>/*</url-pattern> <struts> </filter-mapping> <constant name=quot;struts.devModequot; value=quot;truequot; /> </web-app> <package name=quot;testquot; extends=quot;struts-defaultquot; namespace=quot;/testsquot; > ACTIONS <default-interceptor-ref name=quot;basicStackquot; /> Actions are the basic building blocks of Struts: <global-results> <result name=quot;errorquot; type=quot;dispatcherquot;> 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=quot;java.lang.Exceptionquot; result=quot;errorquot; /> </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 quot;successquot;; 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=quot;testMequot; /> configuration-elements.html for the complete list of configuration <action name=quot;updateTestquot; attributes available. method=quot;updatequot;class=quot;com.fdar.s2.MyActionquot; > <result name=quot;successquot; type=quot;dispatcherquot;>/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=quot;altStackquot; /> strutsproperties.html. <exception-mapping exception=quot;java.lang.Exceptionquot; Action Annotations result=quot;exceptionquot; /> The annotations currently available to actions are listed in Table 2. <param name=quot;versionquot;>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=quot;struts-module1.xmlquot; /> @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=quot;successquot; n name—the name of the property for the value to change type= ServletActionRedirectResult.class, value=quot;selectLocationquot;, n value—the new value to assign params={quot;methodquot;,quot;inputquot;}) 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 (quot;.actionquot; 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 quot;executequot;) 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 quot;successquot;) n type (not required)—the result type to use to render the result as their individual attributes, every annotation has the following (defaults to quot;dispatcherquot;) 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 = quot;Please enter a date this yearquot;, key = quot;validate.thisYearquot;, dateRangeFields a list of DateRangeFieldValidators min = quot;2008/01/01quot;, max = quot;2008/12/31quot;) 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 = quot;Please enter a date this yearquot;, regexFields a list of RegexFieldValidator key = quot;validate.thisYearquot;, minInclusive = quot;2008/01/01quot;, expressions a list of ExpressionValidator maxInclusive = quot;2008/12/31quot;) @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 = quot;Please confirm passwordquot;, key = quot;confirm.passwordquot;, fieldname=quot;userNamequot;, shortCircuit = true, message=quot;Username is requiredquot;)}, expression = quot;password.equals(confirmPassword)quot; ) emails = { @FieldExpressionValidator (a) Validates that a field expression evaluates to true. @EmailValidator(fieldName=quot;emailAddressquot;, expression—the OGNL expression to evaluate n message=quot;Email address is requiredquot;)} 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 = quot;Error validating Userquot;, @TypeConversion( key = quot;user.errorquot;, type = ConversionType.APPLICATION, shortCircuit = true, property = quot;java.util.Datequot;, context = quot;modelquot;, appendPrefix = true) converter = quot;com.opensymphony.xwork2.util.XWorkBasic-Converterquot;) @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 =quot;myUserValidatorquot;, fieldName = quot;userquot;, Hot able, although with generics they are mostly parameters = { @ValidationParameter( Tip unused. If you’re interested, the full list can name = quot;sourcequot;, value = quot;adminquot; ) } 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=quot;successquot; type=quot;xsltquot;> n method (not required)—the method on the action to <param name=quot;locationquot;>user.xslt</param> <param name=quot;matchingPatternquot;>^/result/[^/*]$<param> execute (defaults to execute) </result> <result type=quot;chainquot;> <param name=quot;actionNamequot;>listAction</param> Table 5. Available Result Types, continued <param name=quot;namespacequot;>/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=quot;successquot; can be accessed by placing the expression with type=quot;dispatcherquot;>user.jsp</result> or (using the defaults) the quot;${quot; and quot;}quot; 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=quot;successquot; org/2.x/docs/result-types.html. type=quot;freemarkerquot;>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=quot;notAuthorizedquot; type=quot;httpheaderquot;> in Struts2. Table 6 provides a list of all the interceptors available <param name=quot;statusquot;>401</param> in Struts2. <param name=quot;headers.userquot;>${username}</param> <param name=quot;headers.resourcequot;>/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=quot;successquot; type=quot;redirectquot;> n includeMethods: method names to be included in <param name=quot;locationquot;>viewUser.jsp</param> interceptor processing <param name=quot;parsequot;>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=quot;redirectActionquot;> that contains the name-to-alias map (defaults to aliases). <param name=quot;actionNamequot;>dashboard</param> <action name=quot;testquot; class=quot;com.examples.TestActionquot;> <param name=quot;namespacequot;>/secure</param> <param name=quot;aliasesquot;>#{ '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=quot;successquot; type=quot;velocityquot;> <param name=quot;locationquot;>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=quot;successquot; type=quot;streamquot;> an asterisk). n cookiesValue—comma separated list of cookie values to <param name=quot;contentTypequot;>image/jpeg</param> <param name=quot;inputNamequot;>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 the Model- profiling mode is enabled. Interceptor Driven interface on actions) from the action into the Value profilingKey—the key to use to activate profiling n modelDriven Stack 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=quot;breadcrumbquot; Prepare Interceptor (a) Calls a method for pre-execute logic for classes implement- class=quot;com.fdar.BreadCrumbInterceptorquot; /> prepare ing the Preparable interface. The method called is either prepare{methodName}, where {methodName} is usually <interceptor-stack name=quot;appStackquot;> execute, or a generic prepare method. <interceptor-ref name=quot;basicStackquot; /> n alwaysInvokePrepare (not required)—determines whether <interceptor-ref name=quot;breadcrumbquot; /> the prepare method will always be invoked (defaults to true) </interceptor-stack> Table 6. Available Interceptors, continued </interceptors> DZone, Inc. | www.dzone.com
  • 6. 6 Struts2 tech facts at your fingertips Interceptors, continued <action name=quot;testMequot; class=quot;com.fdar.apress.s2.MyActionquot;> <interceptor-ref name=quot;defaultStackquot;> It’s important not only to have the correct <param name=quot;validation.excludeMethodsquot;> Hot interceptors but ensure that they are executed in prepare,findById</param> Tip the correct order. So make sure your interceptor </interceptor-ref> stacks are defined in the order you want the </action> interceptors executed! 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. The parameters for interceptors can be configured in two ways. Parameters can be added using the param tag when configuring Annotation Name Description the interceptor: @After Denotes methods on the interceptor to execute after the execute() <interceptor-ref name=quot;validationquot;> method is invoked. priority (not required)—the order to execute @After annotations n <param name=quot;excludeMethodsquot;>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 AbOUT ThE AUThOr rECOMMENDED bOOK Ian Roughley The latest v2 release of Apache Struts takes Ian Roughley is a speaker, author, and consultant. For more than ten developers’ capabilities to the next level, having integrated Ajax support, the ability to years he has been helping clients ranging in size from Fortune 10 easily integration with the Spring framework, companies to start-ups. Focused on a pragmatic and results-based and the ability to take full advantage of approach, he is a proponent for open source, as well as process and POJOs. Practical Apache Struts 2 Web 2.0 quality improvements through agile development techniques. Projects shows you how to capitalize upon these new features to build next–generation web applications Publications that both enthrall and empower your users. Author of Starting Struts2 and Practical Struts2 Web 2.0 Projects; Java editor for InfoQ.com Web Site Email bUy NOW http://www.fdar.com ian@fdar.com books.dzone.com/books/struts2 Want More? Download Now. Subscribe at refcardz.com Upcoming Refcardz: Available: n Silverlight 2 IntelliJ IDEA JPA n Published September 2008 frEE n n JSF n Core CSS: Part I Published June 2008 n jQuerySelectors Agile Methodologies Design Patterns n Published August 2008 n n Core Java n Core .NET n Flexible Rails: Flex 3 on Rails 2 PHP n Very First Steps in Flex Published May 2008 n Core CSS: Part II C# Windows PowerShell n n n Groovy Dependency Injection in EJB 3 n n Spring Annotations n n JUnit Published July 2008 Published April 2008 n NetBeans IDE 6.1 Java Editor n Spring Configuration GWT Style, Configuration n RSS and Atom n Getting Started with Eclipse and JSNI Reference GlassFish Application Server Getting Started with Ajax Published April 2008 n 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