在用struts2框架处理一个request 请求的时候主要使用三个类,Actions,Interceptors,and Results。可以使用一个或多个XMLdocument来配置
Many Actions share common concerns. Some Actions need input validated. Other Actions may need a file upload to be pre-processed. Another Action might need protection from a double submit. Many Actions need drop-down lists and other controls pre-populated before the page displays.
许多Action都需要同样的一批处理过程,例如一些Action需要 “输入验证(input validated)”,一些Action或许需要以个文件上传的预处理,一些Action可能需要防止重复提交...
The framework makes it easy to share solutions to these concerns using an "Interceptor" strategy. When you request a resource that maps to an "action", the framework invokes the Action object. But, before the Action is executed, the invocation can be intercepted by another object. After the Action executes, the invocation could be intercepted again. Unsurprisingly, we call these objects "Interceptors."
Struts2的框架引入了Interceptor的策略,让这些问题更容易的解决了。当你请求某一个Action的时候,Struts2会调用这个Action对象,但是在ActionInocation调用Action execute方法之前, 会被另一个对象所拦截,当Action的execute方法执行完以后,ActionInvocation被再次拦截,好不吃惊的,我们叫这些对象为Interceptor
- Understanding Interceptors 理解Interceptors
- Configuring Interceptors 配置Interceptors
- Stacking Interceptors 堆叠Interceptors
- Framework Interceptors Struts2框架的Interceptors
- FAQ
- Next: Writing Interceptors 编写Interceptors
Understanding Interceptors 理解Interceptors
Interceptors can execute code before and after an Action is invoked. Most of the framework's core functionality is implemented as Interceptors. Features like double-submit guards, type conversion, object population, validation, file upload, page preparation, and more, are all implemented with the help of Interceptors. Each and every Interceptor is pluggable, so you can decide exactly which features an Action needs to support.
Interceptors能在Action被调用之前执行一些代码,多数Struts2的核型功能都是由Interceptors实现的,类似于防止重复提交,类型转换,验证,文件上传,页面准备等。他们都是在interceptors的帮助下直线的。每一个Interceptor都是可拔插的,所以你可以决定Action所需要的每一个确切的Interceptor
Interceptors can be configured on a per-action basis. Your own custom Interceptors can be mixed-and-matched with the Interceptors bundled with the framework.
Interceptors 能够被配置到单个的action,所以你可以构建自己的Interceptors,并将它们配置到框架的其他的Interceptor中去。
Interceptors "set the stage" for the Action classes, doing much of the "heavy lifting" before the Action executes.
我们可把我Interceptor的角色比喻成 “设置舞台布景的人” 它在Action执行之前,布置Action所需要的一切。
The Interceptors are defined in a stack that specifies the execution order. In some cases, the order of the Interceptors on the stack can be very important.
如图:Interceptors 被有序的定义在一个堆栈中,这意味这Interceptor将按照一定序列的执行,注意:Interceptor执行的顺序非常重要
Configuring Interceptors 在strus.xml中配置Interceptors
<package name="default" extends="struts-default"> <interceptors> <interceptor name="timer" class=".."/> <interceptor name="logger" class=".."/> </interceptors> <action name="login" class="tutorial.Login"> <interceptor-ref name="timer"/> <interceptor-ref name="logger"/> <result name="input">login.jsp</result> <result name="success" type="redirectAction">/secure/home</result> </action>
</package>
Stacking Interceptors 把多个单独的Interceptor配置成一个Interceptor堆栈
With most web applications, we find ourselves wanting to apply the same set of Interceptors over and over again. Rather than reiterate the same list of Interceptors, we can bundle these Interceptors together using an Interceptor Stack.
struts.xml<package name="default" extends="struts-default"> <interceptors> <interceptor name="timer" class=".."/> <interceptor name="logger" class=".."/> <interceptor-stack name="myStack"> <interceptor-ref name="timer"/> <interceptor-ref name="logger"/> </interceptor-stack> </interceptors> <action name="login" class="tutuorial.Login"> <interceptor-ref name="myStack"/> <result name="input">login.jsp</result> <result name="success" type="redirectAction">/secure/home</result> </action> </package>
Framework Interceptors Struts2中的Interceptors
Interceptor classes are also defined using a key-value pair specified in the Struts configuration file. The names specified below come specified in struts-default.xml. If you extend the struts-default package, then you can use the names below. Otherwise, they must be defined in your package with a name-class pair specified in the <interceptors> tag.
拦截器也是使用键值对(key-value)的形式配置在 Strusts的配置文件中,下面的拦截器都是被定义在 struts-default.xml中。如果你继承 struts-default 包,你就可以使用下面这些拦截器了。 不然的话,他们就必须使用name-class对的形式配置在你的struts.xml文件中
Interceptor | Name | Description |
---|---|---|
Alias Interceptor | alias | Converts similar parameters that may be named differently between requests. 在不同请求之间将请求参数在不同的名字间转换而请求内容不变 |
Chaining Interceptor | chain | Makes the previous Action's properties available to the current Action. Commonly used together with <result type="chain"> (in the previous Action). 让前一个Action的属性可以被后一个Action使用 |
Checkbox Interceptor | checkbox | Adds automatic checkbox handling code that detect an unchecked checkbox and add it as a parameter with a default (usually 'false') value. Uses a specially named hidden field to detect unsubmitted checkboxes. The default unchecked value is overridable for non-boolean value'd checkboxes. 添加了checkbox自动处理代码,将没有选中的checkbox的内容设定为false,而html默认情况下不提交没有选中的checkbox |
Cookie Interceptor | cookie | Inject cookie with a certain configurable name / value into action. (Since 2.0.7.) 注入cookie到Action中,用已配置的name,value |
Conversion Error Interceptor | conversionError | Adds conversion errors from the ActionContext to the Action's field errors 将转换错误从ActionContext中添加到Action的错误属性字段中。 |
Create Session Interceptor | createSession | Create an HttpSession automatically, useful with certain Interceptors that require a HttpSession to work properly (like the TokenInterceptor) 自动的创建HttpSession,用来为需要使用到HttpSession的拦截器服务。 |
DebuggingInterceptor | debugging | Provides several different debugging screens to provide insight into the data behind the page. 提供不同的调试用的页面来展现内部的数据状况。 |
Execute and Wait Interceptor | execAndWait | Executes the Action in the background and then sends the user off to an intermediate waiting page. 在后台执行Action,然后给用户展现一个中间的等待页面。 |
Exception Interceptor | exception | Maps exceptions to a result. 将异常定位到一个result中去 |
File Upload Interceptor | fileUpload | An Interceptor that adds easy access to file upload support. 可以更容易的上传文件了 |
I18n Interceptor | i18n | Remembers the locale selected for a user's session. 记住用户的session中的locale信息 |
Logger Interceptor | logger | Outputs the name of the Action. 输出Action的名字 |
Message Store Interceptor | store | Store and retrieve action messages / errors / field errors for action that implements ValidationAware interface into session. 存储和索引 实现ValidationAware接口的Action类 所出现的消息,错误,字段错误等信息。 |
Model Driven Interceptor | modelDriven | If the Action implements ModelDriven, pushes the getModel Result onto the Value Stack. 如果Action实现了ModelDriven接口, 拦截器将把Action中的getModel的结果添加到ValueStack中去 |
Scoped Model Driven Interceptor | scopedModelDriven | If the Action implements ScopedModelDriven, the interceptor retrieves and stores the model from a scope and sets it on the action calling setModel. 如果一个Action实现了ScopedModelDriven,则这个拦截器会从相应的Scope中取出model调用Action的setModel方法将其放入Action内部。 |
Parameters Interceptor | params | Sets the request parameters onto the Action. 将请求中的参数设置到Action中去 |
Prepare Interceptor | prepare | If the Action implements Preparable, calls its prepare method. 如果Acton实现了Preparable接口,则该拦截器调用Action类的prepare方法。 |
Scope Interceptor | scope | Simple mechanism for storing Action state in the session or application scope. 将Action状态存入session和application的简单方法。 |
Servlet Config Interceptor | servletConfig | Provide access to Maps representing HttpServletRequest and HttpServletResponse. 提供访问HttpServletRequest和HttpServletResponse的方法,以Map的方式访问。 |
Static Parameters Interceptor | staticParams | Sets the struts.xml defined parameters onto the action. These are the <param> tags that are direct children of the <action> tag. 从struts.xml文件中将<action>中的<param>中的内容设置到对应的Action中。 |
Roles Interceptor | roles | Action will only be executed if the user has the correct JAAS role. 确定用户是否具有JAAS指定的Role,否则不予执行。 |
Timer Interceptor | timer | Outputs how long the Action takes to execute (including nested Interceptors and View) 输出Action实行execute方法花费的时间 |
Token Interceptor | token | Checks for valid token presence in Action, prevents duplicate form submission. 通过Token来避免重复提交,多次提交 |
Token Session Interceptor | tokenSession | Same as Token Interceptor, but stores the submitted data in session when handed an invalid token 和Token Interceptor一样,不过双击的时候把请求的数据存储在Session中 |
Validation Interceptor | validation | Performs validation using the validators defined in action-validation.xml 使用actionName-validation.xml文件中定义的内容校验提交的数据。 |
Workflow Interceptor | workflow | Calls the validate method in your Action class. If Action errors are created then it returns the INPUT view. 调用Action的validate方法,一旦有错误返回,重新定位到INPUT画面 |
Parameter Filter Interceptor | N/A | Removes parameters from the list of those available to Actions 从参数列表中删除不必要的参数 |
Profiling Interceptor | profiling | Activate profiling through parameter 通过参数激活profile |
Multiselect Interceptor | multiselect | Like the checkbox interceptor detects that no value was selected for a field with multiple values (like a select) and adds an empty parameter |