Struts 2

1,549 views

Published on

OGNL
Generic Tags

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,549
On SlideShare
0
From Embeds
0
Number of Embeds
6
Actions
Shares
0
Downloads
34
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Struts 2

  1. 1. Continued….
  2. 2.  OGNL is an expression language that is used to retrieve values from stack.  Normally when actions are called, request parameters, values passed to action, the action bean instance, all are pushed into a stack called as “Value Stack”.  The value stack holds values for the action.  OGNL is used in views to retrieve values from this stack.
  3. 3.  The best thing about struts 2 is OGNL can also be used in the struts.xml file.  The following code specifies how OGNL can be used to specify values in the value stack: <action name=“ShowMail” class=“com.example.ShowMails”> <result>/mails/showMails.jsp?username=${username}</result> </action>  This means when the result page would be rendered the url would be appended with the value retrieved by the username property of the present action class i.e. ShowMails.
  4. 4.  Apart from retrieving data from action class. OGNL helps retrieve data from the following objects:  #application  #session  #request  #attr  #parameters  For example the following code would fetch the value username from the user object in session. <s:property value=“#session.user.username”/>  This in essence is equivalent to: <% User user=session.getAttribute(“user”); Out.println(user.getUsername()); %>
  5. 5.  Functionality for creating views in JSP is provided by Struts in the form of tag library.  The struts tag library is included in the following way in JSP pages that contain struts-tags: <%@taglib uri=“/struts-tags” prefix=“s”%>  The TLD file for the struts tags is present in the jar files of the struts libraries.
  6. 6.  Struts tags fall into these two categories:  Generic Tags: Generic tags control the execution flow when pages are rendered. They are also used to extract data.  UI Tags: UI Tags are used to create user interface elements like form field etc.  Apart from the tag library, Struts 2 also provides OGNL(Object Graph Navigation Language), an intuitive way to retrieve values and embed them in views from the session, action beans etc.
  7. 7.  Generic Tags are of two types:  Data Tags: They are used to retrieve data from objects and display them in web pages.  Control Tags: Control tags are used to emulate loops and decision making constructs like while, for, for and if…else.
  8. 8.  The action tag: This tag is used to invoke some other action from the present page, where it is embedded. Its beneficial when you want some functionality to be invoked in the JSP page without using scriptlets.  Syntax <s:action name=“AuthenticateAction” executeResult=“true”/>
  9. 9. Attribute Meaning Id For referencing the element Name The name of the action that is being called executeResult Whether the result of the action should be displayed or not Namespace Namespace of the action that has to be called Flush Whether the writer should be flushed after execution of this tag var Reference name of the action bean so that it can be used later in the page ignoreContextParams Whether the request parameters are supposed to be included while calling the action
  10. 10.  The property tag: The property tag is used to inject values contained in objects into the JSP page. These values are fetched from the value stack (The value stack is a stack that contains all the objects that the action is dealing with, while the action‟s methods are called).  Syntax: <s:property value=“user.username”/>  Output: Hello Chandrakant
  11. 11. Attribute Meaning id For referencing the element value The value to be displayed default If the attribute is not started then the default value that would appear in its place. escape Whether HTML would be escaped.
  12. 12.  The bean tag: The bean tag is used to instantiate a class that conforms to the java bean specification. It‟s similar to jsp‟s useBean tag.  Syntax <s:bean name=“com.example.Employee” var=“emp”/>
  13. 13. Attribute Meaning id For referencing the element name Name of the class whose instance is supposed to be created. var Name of the reference for the bean object that can be used later on.
  14. 14.  The set tag: This tag is used to set some data into a bean instance or into one of the following:  Session scope  Application scope  Request scope  Page scope  Action(by default)  Syntax <s:set name=“firstName” scope=“session” value=“user.firstName”/>
  15. 15. Attribute Meaning Id For referencing the element name Reference name of the variable that is set in the specified scope. value The value that is set scope The scope in which the value should be placed
  16. 16.  The include tag: This tag is used to include certain JSP page‟s or Servlet‟s result into the present page. Its functionality similar to the jsp include action.  Syntax  <s:include value=“listAllDepartments.jsp”/>
  17. 17. Attribute Meaning value The name of the JSP page or the servlet‟s alias that has to be included in the present page.
  18. 18.  The url tag: The url tag is used to  Render absolute or relative URLs  Handle parameters  Encodes URL‟s so that it can be used in browsers where cookies are disabled.  Syntax <s:url action=“Login.action” var=“loginURL”> <s:param name=“useType” value=“Admin”/> </s:url>
  19. 19. Attribute Meaning Id For referencing the element value The base url action Name of the target Action namespace Namespace of the action that has to be called encode Used to add session id to the url var Reference name of the url so that it can be used later in the page includeParams/include To include the parameters or the context method The method of the action that has to be called Method The method of the action that has to be used Scheme The protocol(http/https)
  20. 20.  The param tag: This tag is used for providing parameters to other tags.  Syntax: <s:param name=“color”>#ff0000</s:param>
  21. 21. Attribute Meaning id For referencing the element name The name of the parameters to be set value Value that has to be set for the parameter
  22. 22.  Control tags used for referencing emulating control structures like loops and decision constructs.  There are basically two control tags  Iterator tag  If, elseif and else tags
  23. 23.  The iterator tag is used for iterating through the collections of objects. The collections can be one of the following types:  Collections  Maps  Enumeration  Iterators  Arrays  Syntax: <s:iterator status=“num” value=“{1, 2, 3, 4, 5}”> <s:property value=“top”/> </s:iterator>
  24. 24. Attribute Meaning Id For referencing the element Value The object to be iterated over Status It is used to mention whether an instance of the IteratorStatus should be pushed into the stack in each iteration.
  25. 25.  The if, elseif and else tags: These tags are used to emulate an if…else if…else construct.  Syntax: <s:if test=“%{#userRole==„Admin‟}”/> <!–- Do something here.. --> </s:if> <s:elseif test=“%{#userRole==„HR‟}”/> <!–- Something else--> -- > <s:else> <!– Do what should be done if all fails. --> </s:else>
  26. 26. Attribute Meaning Id For referencing the element Test The expression of that needs to be tested to determine if body of the tag would be executed.
  27. 27.  UI Tags are used to generate form elements or display data in simple are reusable format.  Tags, themes and templates combine together to produce flexible, feature-rich and extensible UI components.  The struts UI tags are backed by templates that do the actual work.  Templates group together to form themes. The various themes are:  simple  ajax  Xhtml  css_xhtml
  28. 28.  UI Tags are used to create form elements.  The following are few Struts UI Tags: ◦ s:form, s:textfield, s:password, s:hidden, s:textarea, s:submit, s:file, s:checkbox, s:select, s:radio, s:reset
  29. 29.  Views are usually specified in the struts.xml as results of actions. For instance: <action name=“LoginScreen”> <result>login.jsp</result </action>  The result tag has a type attribute that can take the following values:  Redirect – This is specified as the value of type if we want the controller to redirect to a different page on the event of an action‟s result. This can redirect to another JSP page or servlet.  redirectAction – This is similar to redirect, however with redirectAction, the name of some other action can be specified.
  30. 30.  The struts2 validation framework is one of the most comprehensive ones that struts 2 core is composed of.  Struts 2 provides support for both server-side and client-side validation.  A lot of predefined validators and ability to create and plug in custom validators adds to the validation prowess of the framework.  Struts provides both declarative and programmatic validation techniques.
  31. 31.  Programmatic validation is achieved in Action classes by implementing the Validateable interface in the action class.  This interface has the void validate() method, which needs to be overridden.  Validation code is put in this function.  In case the Action class needs to report the validation errors, then it needs to implement the ValidationAware interface that has methods for error logging. These two interfaces are implemented in the ActionSupport class. So extending ActionSupport automatically makes the action class possess validation capabilities. All that needs to be done is overriding of the validate() method and reporting of the validation errors.
  32. 32.  Usually programmatic validation is used in complex validation scenarios.  In case things like pattern of input data, input data length, data type(number or string or email address) have to be validated, declarative validation is a better choice.  Declarative validation is done in xml files that are present in the same directory as the Action class.  These files are named in this manner  <Action class name>-validation.xml  For instance if the name of the Action class is Employee the validation.xml file would be:  Employee-validation.xml
  33. 33. <validators> <field name=“count”> <field-validator type=“int” short-circuit=“true”> <param name=“min”>1</param> <param name=“max”>100</param> <message key=“invalid.count”> value must be between ${min} and ${max} </message> </field-validator> </field> <field name=“name”> … </field> … … </validators>
  34. 34.  Inside the validation xml file there can be multiple <field></field> entries, each corresponding to a property of the action class.  The <field> element may be contain one or more <field-validator> entries. Each of these field-validator represents a validation rule.  The type attribute of the <field-validator< tag specifies what kind of validation is required.  The short-circuit attribute(if set to true) would prevent the rest of the validators from validating.  Param tags can be used to specify validation parameters.
  35. 35.  Validators can either act upon single fields or can act upon the whole action context.  In case a validator has to act upon the whole action context then instead of <field-validator>, the <validator> tag is used.  <validator> has a higher precedence over <field- validator>
  36. 36. Validator type Parameters required fieldName requiredString fieldName, trim stringLength fieldName, maxLength, minLength, trim Int fieldName, min, max Double fieldName, maxInclusive, minExclusive, maxExclusive Date fieldName, max, min Expression Expression fieldExpression Expression Email fieldName url fieldName Conversion fieldName Regex fieldName, expression, caseSensitive, trim
  37. 37.  In case errors are encountered during validation(programmatic or declarative), the result of the action automatically becomes input.  Therefore to handle result of type input, there should be an appropriate element in struts.xml.  For example: <action name=“SaveEmployeeDetails” class=“com.example.Employee”> <result name=“input”>employeeForm.jsp</result> <result name=“success”>saveSuccess.jsp</result> </action>

×