TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
如果要开发自己的拦截器,应该实现com.opensymphony.xwork2.interceptor.Interceptor接口,该接口的定义如下: public interface Interceptor extends Serializable{
//销毁该拦截器之前的回调方法
void destroy();
//初始化该拦截器的回调方法
void init();
//拦截器实现拦截的逻辑方法
String intercept(ActionInvocation invocation) throws Exception;
}
Struts 2提供了一个AbstractInterceptor类,该类提供了一个init和destroy方法的空实现,如果我们实现的拦截器不需要申请资源,则可以继承此类。
下面实例应用要求用户登录,且必须为指定用户名才可以查看系统中某个视图资源;否则,系统直接转入登录页面。
检查用户是否登录,通常都是通过跟踪用户的Session来完成,通过ActionContext即可访问到Session中的属性,拦截器的
intercepte(ActionInvocation invocation)方法的invocation参数可以很轻易地访问到请求相关的ActionContext实例。
权限检查拦截器类的代码如下:- package lee;
- import com.opensymphony.xwork2.ActionInvocation;
- import com.opensymphony.xwork2.ActionSupport;
- import com.opensymphony.xwork2.Action;
- import com.opensymphony.xwork2.ActionContext;
- import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
- import java.util.*;
- /**
- * @author yeeku.H.lee kongyeeku@163.com
- * @version 1.0
- * Copyright (C), 2005-2008, yeeku.H.Lee
- * This program is protected by copyright laws.
- * Program Name:
- * Date:
- */
- public class AuthorityInterceptor extends AbstractInterceptor
- {
- public String intercept(ActionInvocation invocation) throws Exception
- {
- ActionContext ctx = invocation.getInvocationContext();
- Map session = ctx.getSession();
- String user = (String)session.get("user");
- if (user != null && user.equals("scott") )
- {
- return invocation.invoke();
- }
- ctx.put("tip" , "您还没有登陆,请输入scott,tiger登陆系统");
- return Action.LOGIN;
- }
- }
复制代码 它要拦截的动作是viewBook.action,这要在struts.xml中配置
<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.custom.i18n.resources" value="globalMessages"/>
<constant name="struts.i18n.encoding" value="GBK"/> <package name="lee" extends="struts-default">
<interceptors>
<interceptor name="authority" class="lee.AuthorityInterceptor"/>
</interceptors> <global-results>
<result name="login">/login.jsp</result>
</global-results> <action name="login" class="lee.LoginAction">
<result name="error">/error.jsp</result>
<result name="success">/welcome.jsp</result>
</action>
<action name="viewBook">
<result>/WEB-INF/jsp/viewBook.jsp</result>
<!-- 拦截器一般配置在result元素之后! -->
<interceptor-ref name="defaultStack"/>
<interceptor-ref name="authority"/>
</action>
</package>
</struts> 运行图: 
源码下载:http://file.javaxxz.com/2014/10/11/040900343.zip |
|