Struts2 官方教程:编写拦截器
来源:互联网 发布:异或符号 java 编辑:程序博客网 时间:2024/05/18 00:27
拦截器接口
自行编写的拦截器,必须实现com.opensymphony.xwork2.interceptor.Interceptor 接口。
Interceptor.java
public interface Inteceptor extends Serializable{ void destroy(); void init(); String intercept(ActionInvocation invocation) throws Exception();}
init方法在拦截器被实例化之后、调用intercept之前被调用。这是分配任何会被拦截器所使用资源的地方。
intercept方法是拦截器代码被书写的地方。就像一个动作方法,intercept返回一个被Struts用来转发请求到另一个网页资源的结果。使用类型为ActionInvocation的参数调用invoke ,会执行这个动作(如果这是栈之中的最后一个拦截器),或者调用另一个拦截器。
记住,invoke会在结果已经被调用之后返回(例如在你的JSP已经被渲染之后),让类似打开对话框之类的事情变得完美。如果你希望在结果被调用之前就做点什么,淫荡实现一个PreResultListener。
重写destroy,在应用停止时释放资源。
线程安全
拦截器必须是线程安全的!
一个Struts2 动作实例为每个请求都创建,并且不需要是线程安全的。相反地,拦截器是在请求之间共享的,因而必须是线程安全的。
AbstractInterceptor 抽象拦截器
AbstractInterceptor类提供了一个init和destroy空的实现,并且如果这些方法不被实现,也可以被使用。
映射
通过在interceptors元素中嵌套使用interceptor元素来声明拦截器。下面是来自struts-default.xml。
<struts> ··· <package name="struts-default"> <interceptors> <interceptor name="alias" class="com.opensymphony.xwork2.interceptor.AliasInterceptor"/> <interceptor name="autowiring" class="com.opensymphony.xwork2.spring.interceptor.ActionAutowiringInterceptor"/> ···</struts>
示例
假设现有一个类型为”MyAction”的动作,有一个setDate(Date)方法;这里简单的拦截器会设置动作的date为当前时间:
拦截器示例
import com.opensymphony.xwork2.ActionInvocation;import com.opensymphony.xwork2.interceptor.AbstractInterceptor;public class SimpleInterceptor extends AbstractInterceptor{ public String intercept(ActionInvocation invocation) throws Exception{ MyAction action=(MyAction) invocation.getAction(); action.setDate(new Date()); return invocation.invoke(); }}
阅读全文
0 0
- Struts2 官方教程:编写拦截器
- Struts2 官方教程:介绍拦截器
- Struts2拦截器教程
- Struts2.x教程(三) Struts2拦截器
- 编写一个简单的Struts2 拦截器
- struts2编写自定义拦截器filter
- struts2教程- Interceptor(默认拦截器)介绍
- Struts2教程8:拦截器概述
- Struts2教程8:拦截器概述
- struts2教程- Interceptor(默认拦截器)介绍
- Struts2教程8:拦截器概述
- Struts2教程8:拦截器概述
- Struts2教程8:拦截器概述
- struts2教程- Interceptor(默认拦截器)介绍
- struts2教程:15、自定义拦截器
- Struts2教程8:拦截器概述
- Struts2教程8:拦截器概述
- Struts2教程8:拦截器概述
- 堆栈的总结
- 数据结构 插入排序的坑以及思想纠正
- NOIP2015提高组T2 子串
- Node.js
- python mysql问题汇总
- Struts2 官方教程:编写拦截器
- 1041: 最大或 [思维]
- Vue源码解析(四)
- 遇到的HTTP错误 403.14-Forbidden解决办法
- spring+springMVC+Mybatis下的logback日志
- 中国微生物组计划—农作物微生物组:跨越转化临界点的现代生物技术
- UEditor前端配置项说明
- PAT 乙级练习题 1001. 害死人不偿命的(3n+1)猜想 (15)
- HDU