假设有一个web应用,就是简单的有一个简单的登陆页面和登陆成功页面。但是登陆成功页面只允许已经登陆的用户看到。在一个项目中,会有许多这种页面,只允许登陆之后的用户才能访问,如果在每个action中都写上检验用户是否已登陆将会编写大量的重复代码,所以可以定义一个拦截器用来验证用户是否已经登陆成功(通过检验sesison中user的值,前提是每个页面都通过一个action链接) 下面是定义一个拦截器类的方法 import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; /** * 通常我们自定义一个拦截器类需要实现Interceptor接口 * 这个接口中有三个方法void destroy(); void init(); String intercept(ActionInvocation invocation); * 一般只需实现第三个接口即可 * 所以我们可以继承AbstractInterceptor类 * 这个类是实现了这三个接口,同时将第三个接口实现为抽象方法 */ public class AuthenticationInterceptor extends AbstractInterceptor{ public String intercept(ActionInvocation invocation) throws Exception { //判断session里user属性是否null if(invocation.getInvocationContext().getSession().get("User")!=null){ //如果验证通过则继续程序的正常流程 return invocation.invoke(); } else{ //如果验证失败,返回name为input的result return "input"; } } } 在struts.xml中配置拦截器如下 <?xml version="1.0" encoding="UTF-8"?><struts><package name="default" extends="struts-default"><interceptors><!--用户验证拦截器--><interceptor name="authentication" class="interceptor.AuthenticationInterceptor"></interceptor><!--定义一个带用户验证的拦截器栈--><interceptor-stack name="user"><interceptor-ref name="authentication"></interceptor-ref><interceptor-ref name="defaultStack"></interceptor-ref></interceptor-stack></interceptors><!--全局result,登陆页面--><global-results><result name="input">index.jsp</result></global-results><!--根据表单提交数据判断用户是否是授权用户,通过则定向到欢迎aciton--><action name="login" class="action.LoginAction"><result type="redirectAction">welcome</result></action><!--为登陆成功页面设置用户验证拦截器,防止非法访问--><action name="welcome" class="action.WelcomeAction"><result>welcome.jsp</result><interceptor-ref name="user"></interceptor-ref></action></package></struts> 下面是用户验证的action import java.util.Map; //引入action基础类 import com.opensymphony.xwork2.ActionSupport; /** * 该接口是一个声明性质接口,内部无任何内容 * 如果一个类实现了这个接口,在该类里定义一个Map型session变量 * 则类似控制反转,可以在需要的时候直接使用该变量作为当前session进行操作、 * 类似的还有ApplicationAware ParameterAware RequestAware ServletRequestAware ServletResponseAware * 以后我会总结一篇关于这个的文章 */ import org.apache.struts2.interceptor.SessionAware; /** * * @author zhiweiv */ public class LoginAction extends ActionSupport implements SessionAware{ //对应表单的用户名 private String userName; private Map session; //省略set和get方法 @Override public String execute() { //模拟实现,假设用户名为zhiweiv则为认证用户 if (this.getUserName().equals("zhiweiv")){ //如果认证通过则将用户名存入session this.getSession().put("User", userName); return SUCCESS; } else{ //没认证通过则返回输入页面 return INPUT; } } } 代码我传到csdn上了,是用netbeans6.5所写。 http://download.csdn.net/source/638901 http://mygirl1314520.iteye.com/blog/457513
Struts2的自定义拦截器
最新推荐文章于 2021-11-30 17:00:39 发布