struts 2
TRANSCRIPT
3/26/2012
1
Struts 2
Agenda
• Introduction
• Hello World Application
• Struts 2 Validation Framework
• Struts 2 Interceptors Tutorial
Introduction
12.11.08
Struts2
• Elegant, extensible framework for creating enterprise-ready Java web applications.
• Pull-MVC framework. i.e. the data that is to be displayed to user has to be pulled from the Action.
• Supports annotation based configurations
• Action class in Struts 2 act as the model in the web application
• Comes with power APIs to configure Interceptors
• The view part is highly configurable and it supports different result-types such as Velocity, FreeMarker, JSP, etc
3/26/2012
2
Design Patterns used by struts
• Front Controller pattern– is a component looks for all the request for specific url pattern and
routes them into the framework for further processing...
• Command Pattern– comm. with diff components – Ex Action classes
• Composite Pattern– struts tiles
• Decorator Pattern– view solution like freemarker etc
Front Controller
STRUTS 2 BASIC ARCHITECTURE
Controller
FilterDispatcher
ModelAction
(Domain Object/Command obj)
ViewRESULT
(JSP, AJAX)
works as controller
as per design pattern route all
request to the framework
takes control of request and act as model
components
action class act as command pattern
communicate with diff class and decide
what result type is to be forwarded...
Request Processing Lifecycle Request Processing Lifecycle
1. Request send to servlet container
2. Servlet container invokes FilterDispatcher filter which in further determines
appropriate action.
3. One by one Intercetors are applied before calling the Action. Interceptors performs
tasks such as Logging, Validation, File Upload, Double-submit guard etc.
4. Action is executed and the Result is generated by Action.
5. The output of Action is rendered in the view and the result is returned to the user
3/26/2012
3
Struts 2 Arch with interceptor
• Request land to struts framework before it can given to action class...configured interceptor does some pre processing
• Param: responsible for transfer all reqest parameter to the action instances and maintain a copy in values stack...
• validation:• Conversion:• Model driven:
• after all interceptor execute then ....
• Action takes responsibilities to execute some business and logic and return the result. and decide which Result to be displayed, then this display page access value stack with OGNL
• then response is send through interceptor (post processing)
Struts 1 vs Struts 2 in netshell
• Struts 1.X
– it is the ActionServlet which act as a front controller for each req new form bean instance is created
– to hold parameter that access an thread of Action class....
– only one instance of Action
• Struts2• -----------------------------------------------
– It is FilterDispacher that act as front controller ...as request recived a new instance of action – class is created and and param intercepter load all the parameter from the request to the fielf
of action instance
– No seperate form bean to hold the request parameter– Create new instance for each and evey request ; the action can now hold all the request
parameter – can be directy mapped to Action (Hence can work as Domain logic...)
Struts 1.x Action
ControllerActionServlet
FormBean
Action
Struts 2 Action
FrontControllerFilterDispatcher
ActionForm Fields
PARAMS
3/26/2012
4
Advantages of Struts 2
• An Advanced framework with lot of features.
• Based on the MVC Architecture.
• Simple configuration
• Interceptors to reduce the cross cutting functionality
• OGNL
• Pluggable with different Result types like Ajax, JSP, Free Marker, Velocity etc.,
Struts 2 – Behind the scenes
12.11.08 14
Architecture in details
1. The normal lifecycle of struts begins when the request is sent from client.
This results invoke the servlet container which in turn is passed through
standard filter chain.
2. The FilterDispatcher filter is called which consults the ActionMapper to
determine whether an Action should be invoked.
3. If ActionMapper finds an Action to be invoked, the FilterDispatcher
delegates control to ActionProxy.
4. ActionProxy reads the configuration file such as struts.xml. ActionProxy
creates an instance of ActionInvocation class and delegates the control.
Architecture in details…
5. ActionInvocation is responsible for command pattern implementation. It invokes the Interceptors one by one (if required) and then invoke the Action.
6. Once the Action returns, the ActionInvocation is responsible for looking up the proper result associated with the Action result code mapped in struts.xml.
7. The Interceptors are executed again in reverse order and the response is returned to the Filter (In most cases to FilterDispatcher). And the result is then sent to the servlet container which in turns send it back to client.
3/26/2012
5
Architecture in details…
HttpServletRequest – Request goes to servlet container
Filters - various filters are applied
FilterDispatcher – required filter dispacher is called
ActionMapper –dispatcher consults mapper to invoke action or not
ActionProxy – control is passed to proxy and it consults configuration manager for appropriate action and settings and then creates invocation
ActionInvocation – calls interceptors before calling the Action
Interceptors – interceptors do preActions
ActionExecution – Action method is called
ResultsPreparation – result is rendered depending upon the action method response
Interceptors – interceptors are called in reverse order for postActions
Filters – response is passed through filters
HttpServletResponse – response is given to client
12.11.08 17
Agenda
• Introduction
• Hello World Application
• Struts programming practices
• Struts 2 Validation Framework
• Struts 2 Interceptors Tutorial
Hello World Application
12.11.08 12.11.08
3/26/2012
6
12.11.08
at run time ……
12.11.08
Mapping filterdispatcher…
12.11.08
Action analogous to
mini servlet
12.11.08
3/26/2012
7
12.11.08
Success.jsp
Failure.jsp
Agenda
• Introduction
• Hello World Application
• Struts programming practices
• Struts 2 Validation Framework
• Struts 2 Interceptors Tutorial
Struts programming practicesNamespaceMultiple mapping filesStruts 2 actionsDynamic Method Invocation Struts 2 and OGNL
12.11.08
Struts 2 Namespace
• Namespace is a concept to handle the multiple modules by given a namespace to each module.
• In addition, it can used to avoid conflicts between same action names located at different modules
12.11.08
3/26/2012
8
12.11.08
The package
“name” will not
affect the result,
just give a
meaningful name.
12.11.08
Struts 2 action
namespace
map to folder
structure.
Mapping how it works?
12.11.08
Mapping how it works?
12.11.08
3/26/2012
9
Multiple Struts configuration files
• In Struts 2, we should always assign each module a struts configuration file.
• Lets assume that we have two application modules user and audit, In this case, we can create three files :
• struts-audit.xml – Put all audit module settings here.
• struts-user.xml – Put all user modules settings here.
• struts.xml – Put default settings and include the struts-audit.xml and struts-user.xml.
12.11.08 12.11.08
Struts 2 actions
• Struts 2 actions don’t force you to implement any interface or extends class
• Struts 2 comes with an optional action interface (com.opensymphony.xwork2.Action). By implements this interface, it bring some convenient benefits
12.11.08
ActionSupport
• The ActionSupport (com.opensymphony.xwork2.ActionSupport), is a very powerful and convenience class that provides default implementation of few of the important interfaces
12.11.08
3/26/2012
10
Dynamic Method Invocation
• It help us to avoid configuring a separate action mapping for each method in the Action class by using the wildcard method
• AKA short cut can create problems
12.11.08
The word that matches for the first
asterisk will be substituted for the method
attribute. So when the request URL is
"addUser" the add() method in the
UserAction class will be invoked.
Action class
12.11.08
Struts 2 and OGNL
• The automation of data transfer and type conversion is one of the most powerful features of Struts 2. With the help of OGNL, the Struts 2 framework allows transfer of data onto more complex Java-side types like List, Map, etc.
• OGNL is the interface between the Struts 2 framework string-based HTTP Input and Output and the Java-based internal processing.
12.11.08 12.11.08
3/26/2012
11
12.11.08
can get valueStack object inside your
action as follows
12.11.08
Once you have a
ValueStack
object, you can
use following
methods to
manipulate that
object
OGNL
• OGNL is a powerful expression language that is used to
reference and manipulate data on the ValueStack.
• OGNL also helps in data transfer and type conversion.
• The OGNL is very similar to the JSP Expression Language.
• OGNL is based on the idea of having a root or default object
within the context.
• The properties of the default or root object can be referenced
using the markup notation, which is the pound symbol.
12.11.08 12.11.08
3/26/2012
12
12.11.08
Session Management in Struts2
12.11.08
In order to set session-
scoped attributes
within a Struts2 action
class, get hold of the
session map either
through the
ActionContext object
or by implementing the
SessionAware interface
Agenda
• Introduction
• Hello World Application
• Struts programming practices
• Struts 2 Validation Framework
• Struts 2 Interceptors Tutorial
Validation
Define configuration file *-validation.xml or use annotations
className-validation.xml
Place in the directory where .class file is placed
example.Login should have Login-validation.xml
12.11.08 48
<!DOCTYPE validators PUBLIC
"-//OpenSymphony Group//XWork Validator 1.0.2//EN"
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>
<field name="username">
<field-validator type="requiredstring">
<message>Username is required</message>
</field-validator>
</field>
<field name="password">
<field-validator type="requiredstring">
<message>Password is required</message>
</field-validator>
</field></validators>
3/26/2012
13
Introduction to Struts2 Validation Framework
• Struts2 Validation Framework allows us to separate the validation logic from actual Java/JSP code, where it can be reviewed and easily modified later.
• Struts Action 2 relies on a validation framework provided by Xwork
• The Struts2 Validation Framework alleviates much of the headache associated with handling data validation, allowing you to focus on validation code and not on the mechanics of capturing data and redisplaying incomplete or invalid data
• Validation framework comes with set of useful routines to handle form validation automatically and it can handle both server side as well as client side form validation. If certain validation is not present, you can create your own validation logic by implementing java interface com.opensymphony.xwork2.Validator and plug it into validation framework as a re-usable component
Introduction to Struts2 Validation Framework
• Validator uses XML configuration files to determine which validation routines should be installed and how they should be applied for a given application. validators.xml file contains all common validators declaration. If validators.xml file is not present in classpath, a default validation file is loaded from path com/opensymphony/xwork2/validator/validators/default.xml.
• The first configuration file, validator-rules.xml, declares the validation routines that should be plugged into the framework and provides logical names for each of the validations. The validator-rules.xml file also defines client-side JavaScript code for each validation routine. Validator can be configured to send this JavaScript code to the browser so that validations are performed on the client side as well as on the server side.
Validators Scope
• There are two types of Validators in Struts2 Validation Framework.
1. Field Validators
2. Non-field validators
Field validators
• Field validators, as the name indicate, act on single fields accessible through an action.
• A validator, in contrast, is more generic and can do validations in the full action context, involving more than one field (or even no field at all) in validation rule.
• Most validations can be defined on per field basis. This should be preferred over non-field validation wherever possible, as field validator messages are bound to the related field and will be presented next to the corresponding input element in the respecting view
<validators><field name="bar">
<field-validator type="required"><message>You must enter a value for bar.</message>
</field-validator></field>
</validators>
3/26/2012
14
Non-field validators
• Non-field validators only add action level messages. Non-field validators are mostly domain specific and therefore offer custom implementations. The most important standard non-field validator provided by XWork is ExpressionValidator
<validators>
<validator type="expression">
<param name="expression">foo lt bar</param>
<message>Foo must be greater than Bar.</message>
</validator>
</validators>
Struts2 Validation getting started…
• Will Create an Action class called CustomerAction which will contain few fields
CustomerAction.javapackage net.viralpatel.struts2;
import com.opensymphony.xwork2.ActionSupport;
public class CustomerAction extends ActionSupport{private String name;private Integer age;private String email;private String telephone;
public String addCustomer() {return SUCCESS;
}
public String getName() {
return name;}public void setName(String name) {
this.name = name;}public Integer getAge() {
return age;}public void setAge(Integer age) {
this.age = age;
}public String getEmail() {
return email;}public void setEmail(String email) {
this.email = email;}public String getTelephone() {
return telephone;}
public void setTelephone(String telephone) {this.telephone = telephone;
}}
add entry for this new action class in struts.xml
file• Open the struts.xml file which will be present
under resources folder. And add following content between <package></package> tag.
<action name="customer"
class="net.viralpatel.struts2.CustomerAction">
<result name="success">SuccessCustomer.jsp</result>
<result name="input">Customer.jsp</result>
</action>
3/26/2012
15
• Note that we are mapping the CustomerAction class with name customer.
• Also on success user will be redirected to SuccessCustomer.jsp page. Notice that there is another result tag with name input.
• Whenever the validation logic encounter some validation error, it redirects the user back to page specified as input. Thus in our example, user will be redirected back to Customer.jsp in case of any errors.
• Create two new JSPs Customer.jsp (which will contain Customer form) and SuccessCustomer.jsp (which will be displayed on success)
Customer.jsp<%@ page contentType="text/html; charset=UTF-8"%><%@ taglib prefix="s" uri="/struts-tags"%><html><head><title>Customer Form - Struts2 Demo </title></head>
<body><h2>Customer Form</h2>
<s:form action="customer.action" method="post"><s:textfield name="name" key="name" size="20" /><s:textfield name="age" key="age" size="20" /><s:textfield name="email" key="email" size="20" /><s:textfield name="telephone" key="telephone" size="20" /><s:submit method="addCustomer" key="label.add.customer" align="center" />
</s:form></body></html>
SuccessCustomer.jsp<%@ page contentType="text/html; charset=UTF-8"%><%@ taglib prefix="s" uri="/struts-tags"%><html><head><title>Customer Page - Struts2 Demo </title></head>
<body><h2>Customer Added Successfully.</h2>
</body></html>
create a link to Customer.jsp from Welcome.jsp page.<s:a href="Customer.jsp">Add Customer</s:a>
Now change ApplicationResources.properties
filename= Nameage= Ageemail= Emailtelephone= Telephonelabel.add.customer=Add Customer
errors.invalid=${getText(fieldName)} is invalid.errors.required=${getText(fieldName)} is required.errors.number=${getText(fieldName)} must be a
number.errors.range=${getText(fieldName)} is not in the range
${min} and ${max}.
3/26/2012
16
Adding Validation Logic
• Following will be the validations rules:• Name field is mandatory
• Age field is mandatory. It should be a number between 1 and 100.
• Email field is mandatory. It should be a valid email address.
• Telephone is mandatory.
Defining validation xml files. The format is <ActionClassName>-validation.xml
• create a file CustomerAction-validation.xml
CustomerAction-validation.xml<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC"-//OpenSymphony Group//XWork Validator 1.0.2//EN""http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators><field name="name">
<field-validator type="requiredstring"><param name="trim">true</param><message key="errors.required" />
</field-validator></field><field name="age">
<field-validator type="required"><message key="errors.required" />
</field-validator><field-validator type="int">
<param name="min">1</param><param name="max">100</param><message key="errors.range"/>
</field-validator></field><field name="email">
<field-validator type="requiredstring"><message key="errors.required" />
</field-validator><field-validator type="email">
<message key="errors.invalid" /></field-validator>
</field><field name="telephone">
<field-validator type="requiredstring"><message key="errors.required" />
</field-validator></field>
</validators>
Client Side Validation
• It is very easy to add Client Side validation or JavaScript validation to any form in Struts2.
• All you have to do is to add validate=”true” in form tag in your JSP file.
<s:form action="customer.action" method="post" validate="true">
...
</s:form>
3/26/2012
17
Agenda
• Introduction
• Hello World Application
• Struts programming practices
• Struts 2 Validation Framework
• Struts 2 Interceptors Tutorial
Interceptors
Can execute code before and after execution
Are thread-safe
Can be used for
Validation
Pre populating fields
Double-submit prevention
Session control
Authentication
Type conversion
12.11.08 67
Interceptors
• Struts2 comes with default list of Interceptors already configured in the application in struts-default.xml file. We can create our own custom Interceptors and plugin into a Struts2 based web application.
• Framework creates an object of ActionInvocation that encapsulates the action and all the interceptors configured for that action.
• Each interceptors are called before the action gets called. Once the action is called and result is generated, each interceptors are again called in reverse order to perform post processing work.
• Interceptors can alter the workflow of action. It may prevent the execution of action.
3/26/2012
18
12.11.08
Mapping interceptor to actions
12.11.08
Important to note…
12.11.08
Custom interceptor
• Steps1. Create a class that implements Interceptor.
and Implement the intercept(ActionInvocation invocation) method.
2. Configure the interceptor in the struts.xml and Link it to action.
12.11.08
3/26/2012
19
Step 1:
12.11.08
Create a class that
implements
com.opensymphony.xwork
2.interceptor.Interceptor.
Implement the
intercept(ActionInvoca
tion invocation)
This is the method responsible for
calling the next interceptor or the
action
12.11.08
Step 2:
12.11.08
Configure the interceptor in the
struts.xml and Link it to
action.
Interceptor will execute…
12.11.08