Apache Struts 2 Advance
Upcoming SlideShare
Loading in...5

Apache Struts 2 Advance



Struts 2 Advance

Struts 2 Advance



Total Views
Views on SlideShare
Embed Views



0 Embeds 0

No embeds



Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
Post Comment
Edit your comment

Apache Struts 2 Advance Apache Struts 2 Advance Presentation Transcript

  • Going far beyond
  • ActionContext and OGNL The ActionContext stores ValueStack which stores request data. The ActionContext contains all of the data available to theframework’s processing of the request, including things rangingfrom application data to session- or application-scoped maps. All application specific data are held in the ValueStack, one ofthe objects in the ActionContext. All OGNL expressions must resolve against one of the objectscontained in the ActionContext. By default, the ValueStack will be the one chosen for OGNLresolution, but can specifically name one of the others, such asthe session map. The ActionContext provides a notion of simple container for allthe important data and resources surrounding the execution ofan action. The ValueStack holds your application’s domain-specific data fora given action invocation. The OGNL expression requires a root object contained in theActionContext, against which resolution of references begin.
  • Objects and Maps in ActionContext parameters: Map of request parameters for therequest. request: Map of request-scoped attributes. session: Map of session-scoped attributes. application: Map of application-scoped attributes. attr: Returns first occurrence of attribute occurring inpage, request, session, or application scope, in suchsequence. ValueStack: Contains all the application-domain–specific data for the request.
  • ActionContext and OGNL An OGNL expression must choose one of the objectsin the ActionContext to use as its root object. By default, the ValueStack serves as the root object forresolving all OGNL expressions. OGNL expression can be written in following syntax: #session[user] The # operator tells OGNL to use the named object,located in its context, as the initial object for resolvingthe rest of the expression.
  • The ValueStack: a virtual object When Struts 2 receives a request, it immediately creates anActionContext, a ValueStack, and an action object. As a carrier of application data, the action object is quicklyplaced on the ValueStack so that its properties will beaccessible, via OGNL. There are no infrastructural objects, such as Servlet API orStruts 2 objects, on the ValueStack. The ValueStack pretends to be a single object when OGNLexpressions are resolved against it. The virtual object contains all the properties of all theobjects that have been placed on the stack. If multiple the occurrences of the same property exist,those lowest down in the stack are hidden by theuppermost occurrence of a similarly named property.
  • Struts Tags The tag API specifies the attributes and parametersexposed by the tag. Interfaces to the tag API are implemented in JSP, Velocity,or FreeMarker. While setting the attributes in a tag, If an attribute is oftype String, then its value is interpreted as a string literal inJSP or Velocity. If an attribute is some non-String type (i.e. points to someproperty on the ValueStack), then the value of the attributeis interpreted as an OGNL expression. <s:property value="nonExistingProperty"default="doesNotExist" /> displays “doesNotExist” whennonExistingProperty doesn’t exist in ValueStack. A string attribute to be interpreted as an OGNL expressionby using the %{expression} syntax.
  • Data Tags Data tags let you get data out of the ValueStack or place variablesand objects onto the ValueStack. They are the property, set, push, bean, and action tags. The property tag provides a quick way of writing a property onValueStack or in ActionContext into the rendering HTML. It has attributes value, default (used when values is null) andescape (whether to escape HTML). The set tag assigns a property to another name. It has attributesname, scope (application, session, request, page, or action asdefault),value (expresson of value). A named object in ActionContext can be referenced as a toplevelnamed object with an OGNL expression such as #myObject. The push tag allows you to push properties onto the ValueStackand has opening and closing tags containing toplevel propertiesfrom ValueStack. The bean tag is like a hybrid of the set and push tags. Aninstance of an object can either be pushed onto the ValueStackby default or set a top-level reference to it in the ActionContext.
  • Data Tags: Action Tag Action tag allows to invoke another action from the view layer. The executeResult attribute, allows to indicate whether the resultfor the secondary action should be written into the currentlyrendering page, and the name and namespace attributes, bywhich the secondary action is identified to be fired. By default, the namespace of the current action is used. name: The action name, is of type string. namespace: The action namespace of type string; defaults tothe current page namespace. var: Reference name of the action bean for use later in the page. executeResult: When set to true, executes the result of theaction (default value: false). flush: When set to true, the writer will be flushed upon end ofaction component tag (default value: true) ignoreContextParams: When set to true, the requestparameters are not included when the action is invoked (defaultvalue: false).
  • Control Tags: Iterator Tag The iterator tag allows to loop over collections of objects. It also provides the ability to define a variable in theActionContext, the iterator status, lets it determine certain basicinformation about the current loop state such as loop odd oreven rows. The value attribute specifies the object to be looped over and thestatus specifies an IteratorStatus object placed in the actioncontext with the name as value of the attribute. IteratorStatus object consists information such as the size,current index, and whether the current object is in the even orodd index in the list. The if and else tags provide a familiar if else control logic. They have one Boolean attribute called test, that is evaluated fortrue or false. <s:if test="user.age > 35">This user is too old.</s:if> <s:elseif test="user.age < 35">This user is too young</s:elseif> <s:else>This user is just right</s:else>
  • Miscellaneous Tags The include tag allows to execute a Servlet API–style include,allowing to include the output of any another web resource inthe currently rendering page. The include tag takes the attribute name of the page, action,servlet, or any reference able URL. It provides native access to the ValueStack and a more extensibleparameter model. The URL tag supports URL management from controllingparameters to automatically persisting sessions in the absence ofcookies. <s:url action="IteratorTag" var="myUrl"> <s:param name="id" value="2"/> </s:url> <a href=<s:property value="#myUrl" />> Click Me </a> The param tag specifies querystring parameters to be added tothe generated URL. The includeParams attribute specifies whether parametersfrom the current request are carried over into the new URL.
  • Miscellaneous Tags The text tag is used to display language-specific text, suchas English or Spanish, based on a key lookup into a set oftext resources. It retrieves a message value from the ResourceBundlesexposed through the framework’s own internationalizationmechanisms. The i18n tag is used to manually specify ResourceBundleto be used in the test tag. <s:i18nname="maning.chapterSix.myResourceBundle_tr"> In <s:text name="language"/>, <s:text name="girl" var="foreignWord"/></s:i18n> "<s:property value="#foreignWord"/>" means girl. The param tags is a means for passing parameters into thecustom utility objects.
  • Results The result is the encapsulation of the MVC view concerns of theframework. The Action class manages the applications state, while theResult Type manages the view. By default, the framework uses a result type which works withJSPs to render the response pages. The result, the dispatcher result, makes all the ValueStack dataavailable to the executing JSP page. <action name="HomePage" class=". . . HomePage"> <result>/chapterEight/HomePage.jsp</result> </action> A result is the element into which you stuff the location of theJSP page.
  • Predefined Result Types The framework provides several implementations ofthe com.opensymphony.xwork2.Result interface.Chain Result Used for Action ChainingDispatcher Result Used for web resource integration, including JSP integrationFreeMarker Result Used for FreeMarker integrationHttpHeader Result Used to control special HTTP behaviorsRedirectResult Used to redirect to another URL (web resource)Redirect ActionResult Used to redirect to another action mappingStream ResultUsed to stream an InputStream (raw data) back to the browser(usually for file downloads)Velocity Result Used for Velocity integrationXSL Result Used for XML/XSLT integrationPlainText Result Used to display the raw content of a particular page (i.e jsp, HTML)Tiles Result Used to provide Tiles integration
  • Chain Result This result invokes an entire other action, complete with its own interceptorstack and result. <package name="public" extends="struts-default"> <!-- Chain creatAccount to login, using the default parameter --> <action name="createAccount" class="..."> <result type="chain">login</result> </action> <action name="login" class="..."> <!-- Chain to another namespace --> <result type="chain"> <param name="actionName">dashboard</param> <param name="namespace">/secure</param> </result> </action> </package> <package name="secure" extends="struts-default" namespace="/secure"> <action name="dashboard" class="..."> <result>dashboard.jsp</result></action> </package>
  • Dispatcher Result Includes or forwards to a view (usually a jsp). Behind the scenes Struts will use a RequestDispatcher,where the target servlet/JSP receives the samerequest/response objects as the original servlet/JSP. Data can be passed between them usingrequest.setAttribute() - the Struts action is available. <result name="success" type="dispatcher"> <param name="location">foo.jsp</param> </result>
  • FreeMarker and Velocity Result FreeMarker: Renders a view using the Freemarker template engine. The FreemarkarManager class configures the template loaders so thatthe template location can be either relative to the web root folder.eg /WEB-INF/views/home.ftl or a a classpath resuorce.eg /com/company/web/views/home.ftl. <result name="success“ type="freemarker"> foo.ftl </result> Velocity: Using the Servlet containers JspFactory, this result mocks aJSP execution environment and then displays a Velocity template bystreamming directly to the servlet output. <result name="success" type="velocity"> <param name="location">foo.vm</param> </result>
  • HttpHeader Result A custom Result type for setting HTTP headers and status byoptionally evaluating against the ValueStack. The result can also be used to send and error to the client. <result name="success" type="httpheader"> <param name="status">204</param> <param name="headers.a">a custom header value</param> <param name="headers.b">more custom header value</param> </result> <result name="proxyRequired" type="httpheader"> <param name="error">305</param> <param name="errorMessage">accessed through prozy</param> </result>
  • Adding Spring to Struts 2 Spring can handle the objects created by Struts 2 by providing aSpring extension of the Struts 2 ObjectFactory, the class thatcreates each of the objects used in the framework. A Spring plug-in is added to the framework providing a Springextension of the core ObjectFactory. Spring provides the opportunity to manage the creation of anyobjects that the struts framework creates. The plug-in struts2-spring-plugin-2.0.9.jar and spring.jar areadded to the lib directory. The Spring container is created using a Spring application-context listener in the Spring JAR and is set up with thefollowing snippet from the web.xml file: <listener> <listener-class>org.springframework.web.context.ContextLoaderListener </listener-class> </listener>
  • Adding Spring to Struts 2 In order for the Spring to handle the objects, the objects are declared asSpring beans in a Spring configuration file. The ContextLoaderListener by default looks up for the config file in/WEB-INF/applicationContext.xml. Spring is given information to manage the object in theapplicationContext.xml. By default, Spring beans are created as singletons, which won’t work forStruts 2 actions, because they carry data related to each individualrequest, hence scope is set to prototype force Spring to create a uniqueinstance for each request. <bean id="portfolioService“ class="main.chapterNine.utils.PortfolioServiceJPAImpl"/> <bean id="springManagedLoginAction" class="main.chapterNine.Login“ scope="prototype"> <property name="portfolioService" ref="portfolioService"/> </bean> </beans>
  • Adding Spring to Struts 2 Spring creates one of its beans after referring to the Spring bean’sID from within the Struts 2 action mapping, as follows: <action name="Login" class="springManagedLoginAction"> <result type="redirectAction"> <param name="actionName">AdminPortfolio</param> <param name="namespace">/chapEight/secure</param> </result> <result name="input">/chapEight/Login.jsp</result> </action> The framework asks Spring for a bean going by the name ofspringManagedLoginAction and Spring gladly returns that beanwith the PortfolioService injected and ready to go.
  • Validation Framework Architecture The validation framework provides a more versatile andmaintainable solution to validation than the Validateableinterface. The Validator is the stronger points of the validationframework which is a reusable component in which thelogic of specific types of validations are implemented. The three main components in the validation frameworkare: the domain data, validation metadata, and thevalidators. DOMAIN DATA: The domain data is the properties of aStruts 2 action. These properties are assumed to hold the data for theaction to work with when it begins execution. The domain data could also be implemented in variousways such as via a ModelDriven action for instance.
  • Validation Framework Architecture VALIDATION METADATA: A middle component lies between the validators and the dataproperties. Such middle component is the metadata that associates individual dataproperties with the validators that should be used to verify thecorrectness of the values in those properties at runtime. Many validators can be associated with each property, including zero ifthat makes sense for the requirements. The developer can map data properties to validators with XML files(ActionClass-validations.xml)or with Java annotations. VALIDATORS: A validator is a reusable component that contains the logic forperforming some fine-grained act of validation. The framework comes with a rich set of built-in validators such asstringlength validator. To validate the data by the validators, the properties need to be wiredup to the desired validators via some XML or Java annotations. When the validation executes, each property is validated by the set ofvalidators with which it’s been associated by the metadata layer.
  • Basic Validation The actions extend ActionSupport class, which implements a couple ofinterfaces that play an important role in validation. The interfaces are com.opensymphony.xwork2.Validateable andcom.opensymphony.xwork2.ValidationAware. Validateable exposes the validate() method, in which resides thevalidation code, and ValidationAware exposes methods for storingerror messages generated when validation finds invalid data. These interfaces work in tandem with the workflow interceptor. When the workflow interceptor fires, it first checks to see whether theaction implements Validateable. If it does, the workflow interceptor invokes the validate() method. If the validation code finds that some piece of data isn’t valid, an errormessage is created and added to one of the ValidationAware methodsthat store error messages. When the validate() method returns, the workflow interceptor and stillhas another task, it calls ValidationAware’s hasErrors() method to see ifthere were any problems with validation. If errors exist, the workflow interceptor intervenes by stopping furtherexecution of the action by returning the input result, which returns theuser back to the form that was submitted.
  • Validation Framework The validation interceptor, which follows the conversionError interceptor inthe defaultStack, provides the entry point into this validation process. When the validation interceptor is fired, it conducts all the validation that’sbeen defined via the validation metadata. If the validation is not true then an error is added to the ValidationAwaremethods. Note that both conversion errors and validation errors are collected byValidationAware. Whether errors are added or not, it still proceeds to the next interceptor, theworkflow interceptor. The workflow interceptor first invokes the validate() method, if exposed by thecurrent action in basic validation. The workflow interceptor then checks for errors, by checking theValidationAware method hasErrors(). If there are no errors, it passes control on to the rest of the action invocationprocess. If errors are found, workflow is diverted and it returns to the input page andpresent the user with error messages. The basic validation methods and the validation framework can be used at thesame time.
  • Sample Validation Metadata File <validators> <field name="password"> <field-validator type="requiredstring"> <message>You must enter a value for password.</message> </field-validator> </field> <field name="username"> <field-validator type="stringlength"> <param name="maxLength">8</param> <param name="minLength">5</param> <message>While ${username} is a nice name, a valid username must be between ${minLength} and ${maxLength} characters long. </message> </field-validator> </field> <validator type="expression"> <param name="expression">username != password</param> <message>Username and password cant be the same.</message> </validator> </validators>
  • Field Validators Field validators are validators that operate on anindividual field or data property. The fields are the HTML form fields that submittedthe request. The field-validator elements are inside the fieldelement to declare which validators should validatethis piece of data. A field element can have more than one fieldvalidators.
  • Non Field Validators Non field validators don’t apply logic targeted at aspecific field. Such validators apply to the whole action and oftencontain checks that involve more than one of the fieldvalues. The built-in validators only offer one instance of anonfield validator: the expression validator. The expression validator allows to embed an OGNLexpression containing the logic of the validation toperform and resolves against the ValueStack.
  • The Message Element The message element is used to specify the message that theuser should see in the event of a validation error. OGNL expressions can be used to make the messsage dynamic,and are resolved againist the ValueStack. OGNL in the XML files uses the $ rather than the % sign that’snormally used in OGNL. The message can be externalize in a resource bundle as localizedmessages. The ActionSupport implements the TextProvider interface toprovide access to localized messages, and can be accessed by theTextProvider’s getText() method from the validate() method. The message element doesn’t have a text body but, it sets the keyattribute to a value to be used to look up the message via theTextProvider implementation in the ActionClass.properties file.
  • Struts 2 Built-in ValidatorsValidator Params Functionrequired None Verifies that value is non-null.requiredString trim Verifies value is non-null, & not an empty stringstringlength trim,min,max Verifies string length falls within the paramsint min, max Verifies integer value falls between min & maxdouble minIn,maxIn,minEx, maxExVerifies double value falls between theinclusively or exclusively specified parameters.date min, max Verifies date value falls between min & maxemail None Verifies email address format.url None Verifies URL format.fieldexpression expression Evaluates OGNL expression against ValueStack.expression expression Same as fieldexpression, used at actionlevel.Visitor Context,appendPrefixDefers validation of a domain object property,to validations made local to domain object.regex exp, trim,caseSensitiveVerifies String conforming to regular expression
  • Writing a Custom Validator All validators are obligated to implement the Validator orFieldValidator interface. One can extend either ValidatorSupport or FieldValidatorSupport,from the validators package to write a custom tag. A nonfield validator, which performs a validation check involving morethan one field, is written by extend ValidatorSupport class. The validation code is specified in the validate() method. The validator also needs to create JavaBeans properties to match allparameters to be exposed to the user. The following snippet shows parameter passing from the XML file tothe property: <field-validator type="passwordintegrity"> <param name="specialCharacters">$!@#?</param> <message>Password must have 1 of foll "${specialCharacters}". </message> </field-validator>
  • Writing a Custom Validator Most of the helper methods are actually defined inValidatorSupport, which is extended by FieldValidatorSupport. The Field name and value is retrieved by calling helper methods,getFieldName() and getFieldValue() defined inFieldValidatorSupport class. Error storing methods are inherited from support classes. The custom validators are declared in an application-localvalidators.xml file, placed in the root of the classpath—directlyunder the src folder in the WEB-INF/classes/. <validators> <validator name="passwordintegrity" class="manning.utils.PasswordIntegrityValidator"/> </validators>
  • Apache Struts 2 Framework An initial request goes to the Servlet container (such as Jetty orResin) which is passed through a standard filter chain. The chain includes the (optional) ActionContextCleanUpfilter, which is useful when integrating technologies such asSiteMesh Plugin. Next, the required FilterDispatcher is called, which in turnconsults the ActionMapper to determine if the request shouldinvoke an action. If the ActionMapper determines that an Action should beinvoked, the FilterDispatcher delegates control to theActionProxy. The ActionProxy consults the framework Configuration Filesmanager (initialized from the struts.xml file). Next, the ActionProxy creates an ActionInvocation, which isresponsible for the command pattern implementation whichincludes invoking any Interceptors (the before clause) inadvance of invoking the Action itself. Once the Action returns, the ActionInvocation is responsiblefor looking up the proper result associated with the Action resultcode mapped in struts.xml.
  • Apache Struts 2 Framework The result is then executed, which often (but not always, as is the casefor Action Chaining) involves a template written in JSP or FreeMarkerto be rendered. Some of those components will work with the ActionMapper torender proper URLs for additional requests. All objects in the architecture (Actions, Results, Interceptors, and soforth) are created by an ObjectFactory which is pluggable. One can provide his own ObjectFactory for any reason that requiresknowing when objects in the framework are created. A popularObjectFactory implementation uses Spring as provided by the SpringPlugin. Interceptors are executed again (in reverse order, calling the afterclause). Finally, the response returns through the filters configured in theweb.xml. If the ActionContextCleanUp filter is present, the FilterDispatcherwill not clean up the ThreadLocal ActionContext. If the ActionContextCleanUp filter is not present, theFilterDispatcher will cleanup all ThreadLocals.