拦截器是用来动态拦截Action调用的对象,允许在一个Action执行前阻止其执行。
自定义一个拦截器类需要实现com.opensymphony.xwork2.interceptor.Interceptor接口:
第一步:新建一个继承com.opensymphony.xwork2.interceptor.Interceptor的拦截器类,如上图
LoginInterceptor.java
public class LoginInterceptor implements Interceptor { public void destroy() { } public void init() { public String intercept(ActionInvocation arg0) throws Exception { <!-- 判断用户是否已登录 --> <!-- 继续执行action中内容 --> <!-- 直接退出action,并返回error--> } |
第二步:配置自定义拦截器:
Struts.xml
<package name="loginpackage" namespace="/test1" extends="struts-default"> <!-- 定义一个拦截器 --> <!-- 自定义拦截器 --> <!-- 定义一个拦截器栈--> <!-- 定义系统核心拦截器,放在自定义拦截器前面,以避免核心拦截器被自定义拦截器覆盖--> <!-- 只对action1_*起作用,可以定义默认拦截器来对所有action都有效--> |
提醒:默认拦截器定义:<default-interceptor-ref name="testStack"/>,可以作用于所有的action。
但当某个action中也配置了拦截器,默认拦截器将不会在该action中实现。
LoginAction.java
public class LoginAction extends ActionSupport{ } |
MyJSP.jsp
<body>
<%=request.getSession().getAttribute("message") %> <br>
</body>
index.jsp
<% request.getSession().setAttribute("user", "zhangsan"); %>
功能实现:用户未登录时(session中user值为空)在跳转到主页面时拦截器会自动进行拦截。
测试:
http://localhost:8080/interceptor/test1/action1_login.action 结果:用户未登录
1.http://localhost:8080/interceptor/index.jsp
2.http://localhost:8080/interceptor/test1/action1_login.action 结果:用户已登录