Apache Struts 2 Framework


Published on

Struts 2 Basics

Published in: Technology, Education
  • Be the first to comment

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Apache Struts 2 Framework

  1. 1. More better implementation of MVC
  2. 2. Struts 2 High Level DesignWeb BrowserClientControllerFilterDispatcherModelActionViewResultrequestrender pageinvoke actionselect result
  3. 3. MVC Components Controller: It maps the requests to actions. The FilterDispatcher acts as controller and is a servletfilter that inspects each incoming request to determinewhich Struts 2 action should handle the request. Model: A model is the internal state of the applicationcomposed of both the data model and the business logic.In struts 2 action acts as model serves two roles: First, an action is an encapsulation of the calls to businesslogic into a single unit of work. Second, the action serves as a locus of data transfer. View: The view referred as Result is the presentationcomponent of the MVC pattern. It is the user interface thatpresents a representation of application’s state to the user.
  4. 4. Struts 2 Request ProcessingAction ResultAction Context (ThreadLocal)ValueStack request session ……..invoke action finishedOGNLOGNLinvoke resultInterceptors
  5. 5. Interceptors The invocation of action passes through the stack ofinterceptors. Every action has a stack of associated interceptors. They are invoked and executed both before and afterthe action or request processing. They provide an architectural component in which todefine various workflow and cross-cutting tasks sothat they can be easily reused as well as separated fromother architectural concerns. Interceptors in Struts 2 perform tasks such as datavalidation, type conversion, and file uploads.
  6. 6. ValueStack and OGNL ValueStack is a storage area that holds all of the dataassociated with the processing of a request. It is the storage area for all application domain datathat will be needed during the processing of a request. Struts 2 keeps all its data in a convenient, centrallocation instead of passing it around. OGNL is the tool that allows to access the data in thecentral repository i.e. the ValueStack. It is the expression language allowing to reference andmanipulate the data in ValueStack. the ValueStack and OGNL are independent of anyindividual framework components.
  7. 7. ActionContext The ActionContext contains all of the data that makes up thecontext in which an action occurs. It includes the ValueStack and key servlet components, request,session and application maps. ValueStack is stored in ThreadLocal context calledActionContext. The ThreadModel makes ActionContext and hence ValueStackaccessible in a single thread of execution. In Struts 2, the processing of each request occurs in a singlethread, as the ValueStack is available from any point in theframework’s handling of a request. The getInvocationContext() method of ActionInvocation returnsthe ActionContext object associated with the request, confiningthe programmatic access to the ActionContext frominterceptors,. The objects in ActionContext can be accessed from view layerpages (JSPs) via OGNL expressions.
  8. 8. Declarative architecture The declarative architecture is one way of configuration in whichactually building Struts 2 applications is the central focus, whileother is more administrative in nature. Each perform foll tasks: 1) Configuring framework: Change the URL extension bywhich the framework recognizes the requests (by default it isaction) or maximum file upload size. 2) Declaring Application framework: Defining struts2components, wiring them to form a workflow path. Declarative architecture is a specialized type of configurationthat allows developers to create an application’s architecturethrough description rather than programmatic intervention. The developer describes the architectural components in high-level artifacts, such as XML files or Java annotations, from whichthe system will create the runtime instance of the application. Declarative architecture can be done in two ways: through XML-based configuration files or through Java annotations.
  9. 9. XML-Based Declarative Architecture XML Declarative Elements: <action name="Register" class="learning.Register"> <result>/RegistrationSuccess.jsp</result> <result name="input">/Registration.jsp</result> </action> An application can have several XML files describingall of the components of the application workingtogether as a large description. The framework uses a specific file as the entry pointinto this large description called the struts.xml file inthe Java classpath.
  10. 10. Java Annotation based Architecture Java annotations allow to add metadata directly to Javasource files. The goal of Java annotations is to support declarativearchitecture elements tools that can read metadata from aJava class and do something useful with that information. @Results({ @Result(name="input", value="/RegistrationSuccess.jsp" ) @Result(value="/RegistrationSuccess.jsp" ) }) public class Login implements Action { public String execute() { //Business logic for login } }
  11. 11. Struts.xml The struts.xml file is an entry point into the XMLdeclarative architecture. <struts> <constant name="struts.devMode" value="true" /> <package name="default" namespace="/" extends="struts-default"> <action name="Menu"> <result>/menu/Menu.jsp</result> </action> </package> <include file="manning/chapterTwo/chapterTwo.xml"/></struts>
  12. 12. Struts.xml A constant element is used to set framework properties. struts.xml can also define some global actions in a defaultpackage. The include element pulls all of included xml documentinto the declarative architecture, to create a single largeXML document. In the action element, each result names a JSP page that isused to render the result page. The struts element is the mandatory document root of allStruts 2 XML files. The package element is an important container element fororganizing the actions, results, and other componentelements. It declares a namespace used to map the URLs tothe actions by the framework. The URL combines the servlet context with the packagenamespace and the action name
  13. 13. Top Level Working The data is both stored in the action and in the ValueStack. First, domain data is always stored in the action. It allows convenient access to data from the action’s execute()method. The framework can access the data, the action object placed onthe ValueStack. All properties of the action are exposed as toplevel properties ofthe ValueStack itself and, is accessible via OGNL. The form field attribute is interpreted as an OGNL expression. The expression is used to target a property on the ValueStack. In the incoming request, the value from the form field isautomatically moved onto that property by the framework. The response JSP page pulls data off from the property on theValueStack by using an OGNL expression, inside a tag.
  14. 14. Using Annotations The annotations are placed directly in the source code of theactions. The location of actions is specified in an initialization parameter“actionPackages” to the Struts 2 FilterDispatcher in web.xml. The action classes are marked which either implement thecom.opensymphony.xwork2.Action interface or use a namingconvention with class names ending with the word Action. The framework makes some assumptions and generates thepackage containing actions with the namespace derived fromnamespace of action class. All annotated actions in the same Java package will be added tothe same Struts 2 package/namespace. Since annotations reside in the action class, the framework takesthe as declaration of an action with its name derived from thejava class. The annotation comes just before the class declaration: @Result(name="SUCCESS",value="/chapterTwo/HelloWorld.jsp" )
  15. 15. Actions Actions encapsulate the unit of work, by the containment ofbusiness logic using the execute() method. In case the logic is complex, it is placed outside in the businesscomponent and injected into the action, Action provide locus of data transfer from the request to theview. Action serves as a centralized data transfer object that can beused to make the application data available in all tiers of theframework. Action merely implements JavaBeans properties for each piece ofdata to carry. Struts 2 creates a new instance of an action for each request thatmaps to it unlike struts 1 were there is only one instance of anaction class. Action returns control string for result routing or selecting theresults to be rendered. The value of the return string must match the name of thedesired result as configured in the declarative architecture.
  16. 16. Organizing using Packages The packages are based upon commonality offunctionality of the components. The packages are declared in the XML files or the Javaannotations located in action class. The package declarations can be for public actions andfor secure actions. The declaration of the secure package is as follows: <package name=“myPkgSecure"namespace="/myPkg/secure"extends="struts-default"> all secure actions </package>
  17. 17. Package Attributes name (required): Name of the package. namespace: Namespace for all actions in package. The namespace is used to find the action. If action doesn’texists on given namespace then it is searched in default orempty namespace. extends: Parent package to inherit from. It names another package whose components should beinherited by the current package. The current package inherits all the members of thesuperclass package and can override them. Most of the intelligent defaults are defined in a built-inpackage called struts-default which can be inherited by extending struts-default. abstract: If true, this package will only be used to defineinheritable components, not actions.
  18. 18. struts-default package The struts-default package, defined in the system’s struts-default.xml file,declares a huge set of commonly needed Struts 2 components ranging fromcomplete interceptor stacks to all the common result types. Contents of the struts-default.xml file: <package name="struts-default"> // package element <interceptor-stack name="defaultStack"> // defaultStack <interceptor-ref name="exception"/> <interceptor-ref name="servlet-config"/> <interceptor-ref name="static-params"/> <interceptor-ref name="params"> // transfers data from request to action <param name="excludeParams">dojo..*</param> </interceptor-ref> <interceptor-ref name="validation"> <param name="excludeMethods">input,back,cancel,browse</param> </interceptor-ref> </interceptor-stack> ………. <default-interceptor-ref name="defaultStack"/> // default interceptor stack ………. </package>
  19. 19. Implementing Actions Struts 2 actions don’t have to implement the Action interface. Any object can informally honor the contract with theframework by simply implementing an execute() method thatreturns a control string. The com.opensymphony.xwork2.Action interface defines themethod: String execute() throws Exception The constants defined by the Action interface are public static final String ERROR "error" public static final String INPUT "input" public static final String LOGIN "login" public static final String NONE "none" public static final String SUCCESS "success"
  20. 20. Implementing Actions <action name="Name"> <result>/chapterOne/NameCollector.jsp</result> </action> The Name action doesn’t specify a class to provide theaction implementation because we just want to go to theJSP page. The Struts 2 intelligent defaults provide a default actionimplementation that is inherited if we don’t specify one. This default action has an empty execute() method thatdoes nothing but automatically return the Actioninterface’s SUCCESS constant as its control string. The framework must use control string to choose a result. The default name attribute for the result element is also theSUCCESS constant, enabling to automatically select theaction.
  21. 21. The ActionSupport class It provides default implementations of the Action interfaceand other useful interfaces, providing data validation andlocalization of error messages. Validation and text localization services are provided via acombination of interceptors and interfaces. The interceptors control the execution of the services whilethe actions implement interfaces with methods that areinvoked by the interceptors. The ActionSupport implements two interfaces thatcoordinate with one of the interceptors from the defaultstack, the DefaultWorkflowInterceptor, to provide basicvalidation.
  22. 22. Declaration of DefaultWorkflowInterceptor <interceptor name="workflow" class="com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor"/> . . . <interceptor-stack name="defaultStack"> . . . <interceptor-ref name="params"/> . . . <interceptor-ref name="workflow"> <param name="excludeMethods"> input,back,cancel,browse </param> </interceptor-ref> . . . <interceptor-stack name="defaultStack">
  23. 23. Basic Validation Process The params interceptor moves the request data onto the actionobject. Then, the workflow interceptor validates the data beforeaccepting it into the model. The workflow interceptor must fire after the params interceptorhas had a chance to move the data on to the action object. When the workflow interceptor fires, it looks for a validate()method on the action to invoke. validate() method is exposed via the Validateable interface. ActionSupport implements the validate() method, which isoverridden by implementation specific validation logic. After all the validation logic has executed, control returns to theworkflow interceptor which checks to see whether any errormessages were generated by the validation logic. If it finds errors, then the workflow interceptor will immediatelyabort the request processing and return the user back to inputform, where appropriate error messages are displayed on theform.
  24. 24. Basic Validation Process The ValidationAware interface defines methods for storingand retrieving error messages. The ActionSupport class provides methods and collectionsof general error messages. addFieldError ( String fieldName, String errorMessage ) addActionError ( String errorMessage ) The workflow interceptor will use methods ofValidationAware interface to determine whether it shouldredirect the workflow back to the input page. If it finds that errors exist, it’ll look for a result with thename input.
  25. 25. Resource Bundles for Message Text ActionSupport implements TextProvider interface to providelocalized message text by providing access to the messages. ActionSupport implements TextProvider’s methods to retrievethe messages from a properties file resource. The TextProvider methods returns the message which isassociated with the key from the properties file, associated withthe action class. The properties file is a simple test file containing a key with itsvalue and located with its Action class. The getText() method is used to retrieve the messages fromproperties files based upon a key. ActionSupport also implements LocaleProvider with a singlemethod getLocale(). The TextProvider, a.k.a. ActionSupport, tries to locate aproperties file for that locale by calling getLocale() ofLocaleProvider.
  26. 26. Transferring Data using Object-backed JavaBeans properties The params interceptor, included in the defaultStack,automatically transfers data from the request to our actionobjects. To enable the transfer, the developer needs to provideJavaBeans properties on the actions, using the same namesas the form fields being submitted. The struts 2 allows to get the already instantiated andpopulated object to the service some object’s methods. Now the validation code must use a deeper notation toreach the data items and there is a change in the fieldnames in the form both at request and response sides. <s:textfield name="user.username" label="Username"/>
  27. 27. Transferring Data using ModelDrivenactions ModelDriven actions expose an application domain object viathe getModel() method, declared by the ModelDriven interface. The method introduces a new interceptor which is alreadypresent in the default stack; the data transfer still beingautomatic. The getModel() method returns the model object, which is sameas the action object. The ModelDriven method needs to initialize the object explicitlyby the developer. The framework obtains a reference to the model object beforethe execute method of ModelDriven action is called. The framework acquires its reference from the getter, it isn’taware of the changes made in the model field internally by theaction causing data inconsistency problems. All references in the JSP pages return to the simplicity of theoriginal action that used the simple, individual JavaBeansproperties for data transfer.
  28. 28. File uploading Struts 2 provides built-in help for file uploading. The default interceptor stack includes FileUpload-Interceptor used for file uploading. The struts-default package contains a declaration of thefileUpload interceptor, backed by FileUploadInterceptorimplementation class. The interceptor is added to the defaultStack so that allpackages extending the struts-default package willautomatically have this interceptor acting on their actions. The defaultstack places the fileUpload interceptor justbefore the params interceptor. When the fileUpload interceptor executes, it processes amultipart request and transforms the file itself, along withsome metadata, into request parameters using a wrapperaround the servlet request.
  29. 29. FileUploadInterceptor Request parameters of the FileUpload interceptor: [file name from form]: File—the uploaded file itself [file name from form]ContentType: String—the content type of the file. [file name from form]FileName : String—the name of the uploaded file, asstored on the server. After the fileUpload interceptor has exposed the parts of the multipart request asrequest parameters, the params interceptor is fired, and it moves all of therequest parameters onto the action object. We set the encoding type of the form to multipart/form-data. which signals tothe framework that the request needs to be handled as an upload. The file is submitted by the form under the name attribute provided in file tag. Uploading multiple files with same parameter names is supported by changingthe action’s JavaBeans properties to arrays The JSP code to upload a file: <s:form action="ImageUpload" method="post" enctype="multipart/form-data"> <s:file name="pic" label="Picture"/> <s:submit/> </s:form>
  30. 30. Interceptors Interceptors implement tasks such as cross-cutting, orpreprocessing and postprocessing. The interceptor sits between controller and action. The invocation of action is a layered process which alwaysincludes the execution of a stack of interceptors prior toand after the actual execution of the action itself. Rather than invoke the action’s execute() method directly,the framework creates an object called anActionInvocation that encapsulates the action and all ofthe interceptors that have been configured to fire beforeand after that action executes. Interceptor instances are shared among actions. Interceptors are stateless. An interceptor just applies its processing logic to the dataof the request, which is already conveniently stored in thevarious objects accessed through the ActionInvocation.
  31. 31. Action Invocation and Interceptors The invocation of an action must first travel through the stack ofinterceptors associated with that action. The normal action ultimately executes and returns a control string thatselects the appropriate result. After the result executes, each of the interceptors, in reverse order, getsa chance to do some postprocessing work. The interceptors have access to the action and other contextual values. The Interceptors is their ability to alter the workflow of the invocationor halt the workflow by itself returning a control string.exceptionmodelDrivenfileUploadparamsworkflowActionResult
  32. 32. ActionInvocation ActionInvocation encapsulates all the processing detailsassociated with the execution of a particular action. When the framework receives a request, it first must decideto which action the URL maps. An instance of this action is added to a newly createdinstance of ActionInvocation. The framework consults the declarative architecture(created by XML or Java annotations), to discover theinterceptors to fire and their sequence. References to these interceptors are added to theActionInvocation. The ActionInvocation also holds references to otherimportant information like the servlet request objects anda map of the results available to the action.
  33. 33. basicStack The first interceptor in the stack, refers to the firstinterceptor declared in the XML as reading from top of thepage down. <interceptor-stack name="basicStack"> <interceptor-ref name="exception"/> <interceptor-ref name="servletConfig"/> <interceptor-ref name="prepare"/> <interceptor-ref name="checkbox"/> <interceptor-ref name="params"/> <interceptor-ref name="conversionError"/> </interceptor-stack>
  34. 34. Interceptors Firing Mechanism The ActionInvocation exposes the invoke() method, called bythe framework to start the execution of the action. ActionInvocation starts the invocation process on calling theinvoke method, by executing the first interceptor in the stack. ActionInvocation keeps track of the stage of the invocationprocess and decides the appropriate interceptor in the stack topass control by calling that interceptor’s intercept() method. The intercept() takes the ActionInvocation instance itself as aparameter. Each time invoke() is called, ActionInvocation consults its stateand executes whichever interceptor comes next in stack(xml)order. The interceptor calls invoke() method recursively to invoke andexecute all the subsequent interceptors until, finally, there areno more interceptors in the stack and the action itself is firedand executed.
  35. 35. intercept() method of TimerInterceptor public String intercept (ActionInvocation invocation)throws Exception { // interceptor’s preprocessing phase long startTime = System.currentTimeMillis(); // decide to pass control on to the rest of the interceptors. String result = invocation.invoke(); // postprocessing phase long executionTime = System.currentTimeMillis() - startTime; ... log the time ... return result; }
  36. 36. Interceptor Execution Cycle The three-stage conditional execution cycle of theinterceptor: Do some preprocessing. Pass control on to successive interceptors, andultimately the action, by calling invoke(), or divertexecution by itself returning a control string. Do some postprocessing. The intercept() method, defined by the Interceptorinterface, is the entry point into an interceptor’sexecution and receives the ActionInvocation instance.
  37. 37. Utility interceptors TIMER: It merely records the duration of anexecution. Position in the interceptor stack determines what thisis actually timing. LOGGER: It provides a simple logging mechanismthat logs an entry statement during preprocessing andan exit statement during postprocessing. It can be useful for debugging. Such interceptors do processing both before and afterthe action executes.
  38. 38. Data transfer interceptors PARAMS (DEFAULTSTACK): It transfers the requestparameters to properties exposed by the ValueStack. The framework uses OGNL expressions, embedded in thename attributes of the form’s fields, to map the datatransfer to those properties. The action is always put on the ValueStack at the start of arequest-processing cycle and properties exposed directlyon the actions. The model, as exposed by the ModelDriven interface, ismoved onto the ValueStack by the modelDriveninterceptor. FILEUPLOAD ( DEFAULTSTACK ): It transforms the filesand metadata from multipart requests into regular requestparameters so that they can be set on the action just likenormal parameters.
  39. 39. Data transfer interceptors STATIC-PARAMS (DEFAULTSTACK): This interceptor moves parameters defined in the actionelements of the declarative architecture onto properties exposedon the ValueStack. In the defaultStack, the static-params interceptor fires before theparams interceptor. Thus the request parameters overrides values from the XMLparam element depending on the order of interceptors. <action name=“oneAction" class="example.oneAction"> <param name="firstName">John</param> <param name="lastName">Doe</param> </action> AUTOWIRING: It provides an integration point for using Springto manage the application and is technically another way to setproperties on the action.
  40. 40. Data transfer interceptors SERVLET-CONFIG ( DEFAULTSTACK ): It provides a clean wayof injecting various objects from the Servlet API into the actions. It works by setting the various objects on setter methods exposedby interfaces that the action must implement. Followinginterfaces are available for retrieving various objects: ■ ServletContextAware—Sets the ServletContext ■ ServletRequestAware—Sets the HttpServletRequest ■ ServletResponseAware—Sets the HttpServletResponse ■ ParameterAware—Sets a map of the request parameters ■ RequestAware—Sets a map of the request attributes ■ SessionAware—Sets a map of the session attributes ■ ApplicationAware—Sets a map of application scope properties ■ PrincipalAware—Sets the Principal object (security) Each of these interfaces contains one method—a setter for theresource. The servlet-config interceptor will put these objects on youraction during the preprocessing phase.
  41. 41. Workflow interceptors Workflow interceptors inspect the state of the processingand conditionally intervene and alter the normal pathslightly or drastically. WORKFLOW (DEFAULTSTACK): It works with theactions to provide data validation and subsequentworkflow alteration if a validation error occurs. The Workflow interceptor can take several parameters: ■ alwaysInvokeValidate (true or false; defaults to true,which means that validate() will be invoked) ■ inputResultName (name of the result to choose ifvalidation fails; defaults to Action.INPUT) ■ excludeMethods (names of methods for which theworkflow interceptor shouldn’t execute, thereby omittingvalidation checking for a specific entry point method on anaction)
  42. 42. excludeMethods The workflow interceptor configured in the defaultStack ispassed a list of excludeMethods parameters, as in thefollowing snippet from struts-default.xml: <interceptor-ref name="workflow"> <paramname="excludeMethods">input,back,cancel,browse</param> </interceptor-ref> The exclude methods is meant to support actions thatexpose methods other than execute() for variousprocessing tasks related to the same data object.
  43. 43. Workflow Interceptors public String intercept(ActionInvocation invocation) throws Exception { Action action = invocation.getAction(); if (action instanceof Validateable) { Validateable validateable = (Validateable) action; validateable.validate(); } if (action instanceof ValidationAware) { ValidationAware validationAwareAction = (ValidationAware) action; if (validationAwareAction.hasErrors()) { return Action.INPUT; } } return invocation.invoke(); }
  44. 44. Workflow interceptors VALIDATION (DEFAULTSTACK): The validation interceptor, is partof the Struts 2 validation framework and provides a declarativemeans to validate data. The validation framework allows use of both XML files and Javaannotations to describe the validation rules for the data. The validation interceptor itself executes the validation logic. The validation interceptor is the entry point into the validationframework’s processing. When the validation framework does its work, it’ll store validationerrors using the same ValidationAware methods as the validate() codedoes. When the workflow interceptor checks for error messages, it doesn’tknow whether they were created by the validation framework or thevalidation code invoked through the Validateable interface. Validation interceptor fires before the workflow interceptor, and thissequencing is handled by the defaultStack.
  45. 45. Workflow interceptors PREPARE (DEFAULTSTACK): The prepareinterceptor provides a generic entry point for arbitraryworkflow processing. When the prepare interceptor executes, it checkswhether the action implements the Preparableinterface, and defines the prepare() method. If the action is Preparable, the prepare() method isinvoked allowing any sort of preprocessing to occur. Even though the prepare interceptor has a specificplace in the defaultStack, one can define his own stackin order to move the prepare code to a differentlocation in the sequence.
  46. 46. Prepare Interceptor The prepare interceptor allows to define special preparemethods for the different execution methods on a singleaction providing more than one execution entry point onthe action. E.g. Action method: input(), Prepare Methods:prepareInput() and prepareDoInput(). When input() method is being invoked, the prepareInput()method is called by the prepare interceptor. The prepare() method itself will always be called by theprepare interceptor regardless of the action method beinginvoked unless turned off by the parameteralwaysInvokePrepare (false) passed to prepare interceptor. The Preparable interface is helpful for setting up resourcesor values before the action is executed.
  47. 47. Workflow interceptors MODELDRIVEN (DEFAULTSTACK): The modelDriven interceptor is considered a workflowinterceptor as it alters the workflow of the execution byinvoking getModel(), if present, and setting the modelobject on the top of the ValueStack where it receives theparameters from the request. By placing the model over the action in the ValueStack, themodelDriven interceptor alters workflow. Such concept of creating an interceptor that canconditionally alter the effective functionality of anotherinterceptor without direct programmatic interventiondemonstrates the power of the layered interceptorarchitecture.
  48. 48. Miscellaneous interceptors EXCEPTION (DEFAULTSTACK): The exceptioninterceptor comes first in the defaultStack. It will catch exceptions and map them, by type, to user-defined error pages. Its position at the top of the stack guarantees that it’ll beable to catch all exceptions that may be generated duringall phases of action invocation as, it’ll be the last to fireduring postprocessing. <global-results> <result name="error">/chapterFour/Error.jsp</result> </global-results> <global-exception-mappings> <exception-mapping exception="java.lang.Exception"result="error"/> </global-exception-mappings>
  49. 49. Miscellaneous interceptors The exception-mapping element tells the exception interceptor whichresult to render for a given exception. The exception interceptor creates an ExceptionHolder object and placeit on top of the ValueStack. The ExceptionHolder is a wrapper around an exception that exposes thestack trace and the exception as JavaBeans properties (exception andexceptionStack) accessible from a tag in error page. TOKEN AND TOKEN-SESSION: The token and token-session interceptors is used as part of a system toprevent duplicate form submissions. Duplicate posts can occur when users click Submit more than once. The token interceptors work by passing a token in with the request thatis checked by the interceptor. If the unique token comes to the interceptor a second time, the requestis considered a duplicate. Both the interceptors do the same thing, differing only in the method ofhandling the duplicate request.
  50. 50. Miscellaneous interceptors SCOPED-MODELDRIVEN (DEFAULTSTACK): Itsupports persistence of the action’s model object acrossseries of requests. It adds to the functionality of the modelDriven interceptorby allowing to store the model object in the session scopefor instance. It helps to implement wizards working with a data objectacross a series of requests. EXECANDWAIT: When a request takes a long time to execute, it’s nice togive the user some feedback. The execAndWait interceptor helps prevent the users fromgetting antsy and provides them with some feedback.
  51. 51. Built-in stacks The struts-default package provides built-in stacks forthe interceptors such as defaultStack to provideconvenient arrangements of the built-in interceptors. The built-in stacks are inherited in the packages byextending the struts-default package defined in struts-default.xml. The unused interceptors don’t affect the performance. Interceptor declarations from the struts-defaultpackage is as follows:
  52. 52.  <package name="struts-default"> . . . <interceptors> <interceptor name="execAndWait" class="ExecuteAndWaitInterceptor"/> <interceptor name="exception" class="ExceptionMappingInterceptor"/> <interceptor name="fileUpload" class="FileUploadInterceptor"/> <interceptor name="i18n" class="I18nInterceptor"/> <interceptor name="logger" class="LoggingInterceptor"/> <interceptor name="modelDriven" class="ModelDrivenInterceptor"/> <interceptor name="scoped-modelDriven" class= . . ./> <interceptor name="params" class="ParametersInterceptor"/> <interceptor name="prepare" class="PrepareInterceptor"/> <interceptor name="static-params" class=. . ./> <interceptor name="servlet-config" class="ServletConfigInterceptor"/> <interceptor name="sessionAutowiring" class="SessionContextAutowiringInterceptor"/> <interceptor name="timer" class="TimerInterceptor"/> <interceptor name="token" class="TokenInterceptor"/> <interceptor name="token-session" class= . . . /> <interceptor name="validation" class= . . . /> <interceptor name="workflow" class="DefaultWorkflowInterceptor"/> . . . <interceptor-stack name="defaultStack"> <interceptor-ref name="exception"/> <interceptor-ref name="alias"/>
  53. 53.  <interceptor-ref name="servlet-config"/> <interceptor-ref name="prepare"/> <interceptor-ref name="i18n"/> <interceptor-ref name="chain"/> <interceptor-ref name="debugging"/> <interceptor-ref name="profiling"/> <interceptor-ref name="scoped-modelDriven"/> <interceptor-ref name="modelDriven"/> <interceptor-ref name="fileUpload"/> <interceptor-ref name="checkbox"/> <interceptor-ref name="static-params"/> <interceptor-ref name="params"> <param name="excludeParams">dojo..*</param> </interceptor-ref> <interceptor-ref name="conversionError"/> <interceptor-ref name="validation"> <param name="excludeMethods">input,back,cancel,browse</param> </interceptor-ref> <interceptor-ref name="workflow"> <param name="excludeMethods">input,back,cancel,browse</param> </interceptor-ref> </interceptor-stack> </interceptors> <default-interceptor-ref name="defaultStack"/> </package>
  54. 54. Declaring Interceptors The interceptors element contains all the interceptor andinterceptor-stack declarations of the package. Interceptor stacks are used to reference a sequenced chunk ofinterceptors by name. Each interceptor element declares an interceptor that can beused in the package by mapping an interceptor implementationclass to a logical name. The contents of the interceptor-stack element are a sequence ofinterceptorref elements which point to one of the logical namescreated by the interceptor elements. The interceptor-ref elements can also pass in parameters toconfigure the instance of the interceptor that is created by thereference. A package can declare a default set of interceptors associatedwith all actions in those packages that don’t explicitly declaretheir own interceptors. The default-interceptor-ref element simply points to a logicalname, such as the defaultStack in struts default package.
  55. 55. Mapping interceptors to actions Associating an interceptor to an action is done with aninterceptorref element. <action name="MyAction" class="org.MyAction"> <interceptor-ref name="timer"/> <interceptor-ref name="logger"/> <result>Success.jsp</result> </action> They are fired in the order they are listed. References to stacks and individual interceptors can becombined to avoid repetition of the same definitions. <interceptor-ref name="defaultStack"/> The actions that don’t define any interceptor-refs inheritthe default interceptors, but as soon as an action declaresits own interceptors, it loses the automatic default andmust explicitly name the defaultStack in order to use it.
  56. 56. Setting and overriding parameters The interceptor-ref element is the place to pass the parameters tothe interceptor. <interceptor-ref name="workflow"> <param name="exMethods">input,back</param> </interceptor-ref> In order to reuse the defaultStack by taking a reference, butchanging the values of its parameter we use following snippet: <action name="YourAction" class="org.act.YourAction"> <interceptor-ref name="defaultStack"> <param name="work.exMethods">doSomething</param> </interceptor-ref> <result>Success.jsp</result> </action>
  57. 57. Building an Interceptor Must implement Interceptor interface to build aninterceptor. public interface Interceptor extends Serializable { void destroy(); // initialize void init(); // clean up String intercept(ActionInvocation invocation); } To build interface having parameter filtering enabledby accepting request parameters, extend theMethodFilterInterceptor class.
  58. 58. OGNL OGNL stands for the Object-Graph NavigationLanguage. OGNL is a technology integrated into the Struts 2framework to help with data transfer and typeconversion. It is the glue between the framework’s string-basedHTTP input and output and the Java-based internalprocessing. OGNL consists of two things from developer’s point ofview: an expression language and type converters.
  59. 59. Expression Language OGNL’s expression language is used in form input field namesand JSP tags. The OGNL expressions bind Java-side data properties to stringsin the text-based view layers, found in the name attributes ofform input fields, or in various attributes of the Struts 2 tags. Struts 2 property tag takes a value from a property of Javaobjectsand writes it into the HTML in place of the tag. It allows to use a simplified syntax to reference objects thatreside in the Java environment. OGNL expressions require no special escaping and Struts 2automatically evaluates the string as an OGNL expression in allcontexts. In contexts where strings are most likely going to be strings, theframework will require the OGNL escape sequence. It helps to move data from the request parameters onto theaction’s JavaBeans properties, and from those properties out intorendering HTML pages.
  60. 60. Type Converters OGNL Type Converters are responsible for conversionbetween the Java type of the property referenced by theOGNL expression language to the string format of theHTML output. Every time data moves to or from the Java environment, atranslation must occur between the string version of thatdata residing in the HTML and the appropriate Java datatype. The built-in type converters allows to map the incomingform fields to a wide variety of Java data types, including allthe primitives as well as a variety of collections.
  61. 61. OGNL role in framework: DATAIN The user enters two values for the fields of the input.html andsubmit the form to the framework. When the request enters the framework, it’s exposed to the Javalanguage as an HttpServletRequest object. The request parameters are stored as name/value pairs, and bothname and value are Strings. The framework handles the transfer and type conversion of thedata from the request parameters. The data object (User) is exposed as JavaBeans property on theaction object. With the action object on the ValueStack, theOGNL can place the data in the data object. The params interceptor will move the data from the requestobject to the ValueStack. OGNL handles the mapping of the name of the parameter to anactual property on the ValueStack. OGNL consults a set of available type converters in theframework to handle any type conversion.
  62. 62. ValueStack The ValueStack is a Struts 2 construct that presents anaggregation of the properties of a stack of objects asproperties of a single virtual object. ValueStack represents the data model exposed to thecurrent request and is the default object against which allOGNL expressions are resolved The ValueStack is a virtual object and holds a stack ofobjects. All the properties of objects in ValueStack appear asproperties of the ValueStack itself. The properties of the higher objects in the stack cover upsimilarly named properties of objects lower in the stack. ValueStack holds the data objects and acts as a place holderfor viewing the data model throughout the various regionsof the framework mostly using OGNL expression language.
  63. 63. Built-in type converters ■ String—A string is just a string. ■ boolean/Boolean—true and false strings can beconverted to both primitive and object versions of Boolean. ■ char/Character—Primitive or object. ■ int/Integer, float/Float, long/Long, double/Double—Primitives or objects. ■ Date—String version will be in SHORT format of currentLocale (for example, 12/10/97). ■ array—Each string element must be convertible to thearray’s type. ■ List—Populated with Strings by default. ■ Map—Populated with Strings by default When the framework locates the Java property targeted by anOGNL expression, it looks for a converter for that type. If converter of such type is in the preceding list, the data isreceived else require a custom type converter.
  64. 64. Multi-Valued Request Parameters Multiple parameter values can be mapped to a single parameter name inthe incoming request. The multivalued request parameters can be transferred to a variety ofcollection-oriented data types, ranging from arrays to actual Collections. Arrays: Struts 2 provides support for converting data to Java arrays withthe help of OGNL support. <s:form action="ArraysDataTransferTest"> <s:textfield name="ages" label="Ages"/> <s:textfield name="ages" label="Ages"/> <s:textfield name="names[0]" label="names"/> <s:textfield name="names[1]" label="names"/> <s:submit/> </s:form> The ages parameter is send as single request parameter with 2 values.The ages array is created and initialized by OGNL. The names parameter is send as 2 parameters with distinct values. TheOGNL interprets the references to names elements in a names arraywhich is pre-initialized.
  65. 65. Request Parameters to Lists Lists: Struts 2 supports automatically converting sets of requestparameters into Lists. By default, the framework will convert request parameters intoStrings and populate the List property with those Strings. When OGNL is informed of the element type for a givenproperty in a properties file (ClassName-conversion.properties),OGNL converts List elements to corresponding property type. With Element-weights=java.lang.Double line in property file, <s:textfield name="weights[0]" label="weights"/> enableseach individual weights element to be converted to a Double. It is not required to preinitialize any of the Lists, even though thedata is received from the indexed OGNL notation. The Struts 2 type conversion mechanism can use generics-basedtyping to learn the correct target type for the conversions. The List should not be preinitialized when using the typedelement conversion mechanism supported by properties file.
  66. 66. Request Parameters to Lists Struts 2 supports automatic conversion of a set of values from arequest into a Map property. The Maps must have a type specified for the key object Both the Map element and key has a default to a String if type isnot specified. Examples of Map property is as follows: <s:textfield name="maidenNames.mary" label="MaidenName"/> <s:textfield name="maidenNames[beth]" label="MaidenName"/> Examples of Map property submitting data as follows: <s:textfield name="myUsers[chad].username"label="Usernames"/> <s:textfield name="myUsers.chad.birthday" label="birthday"/> Similar to element, specifying type for key objects involve addingKey_myOrderedUsers=java.lang.Integer to the property file.
  67. 67. Customizing type conversion Type conversion is a part of OGNL and all type converters mustimplement the ognl.TypeConverter interface. StrutsTypeConverter class is base class which acts as a convenientextension point for custom type conversion. It has following abstractmethods: public abstract Object convertFromString(Map context, String[] values,Class toClass); public abstract String convertToString(Map context, Object o); The string parameter for conversion can be array of strings. Logic consist of string parsing and object creation. Throw a TypeConversionException in case of conversion error. Converter can be configured to be used local to a given action or globally. The ActionName-conversion.properties file is used to specify thecustom converter locally for a specific property with following line:circle=manning.utils.CircleTypeConverter. The xwork-conversion.properties file in WEB-INF/classes/ is used tospecify the custom converter globally for a specific property withfollowing line: manning.utils.Circle=manning.utils.CircleTypeConverter.