一、概述
项目中所有页面均放入WEB-INF,所有页面安全性得到了很大程度的提高。但是当用户登录后长时间没有操作时,会造成Session数据的过期,如果此时获取Session中的数据,必定会引发WEB引用的空指针异常,造成数据错误,程序崩溃。因此需要一种机制保障每次发送请求执行Action中的方法之前校验用户是否处于登录状态。
针对上述分析,可以选用两种实现方式。
AOP
AOP思想可以在任意方法执行前进行拦截,完成原始方法执行前的操作
Struts2拦截器
Struts2拦截器可以再Struts2的任意Action执行之前和之后,完成某些任务,其内部工作原理与AOP极其相似。
二、拦截器实现
2.1、拦截器实现类
package org.sihai.qualitycontrol.util.interceptor;import org.sihai.qualitycontrol.auth.emp.vo.EmpModel;import com.opensymphony.xwork2.ActionContext;import com.opensymphony.xwork2.ActionInvocation;import com.opensymphony.xwork2.interceptor.AbstractInterceptor;public class LoginInterceptor extends AbstractInterceptor{public String intercept(ActionInvocation invocation) throws Exception {//执行除了登录操作之前的所有操作做登录校验//获取本次操作的信息/*System.out.println(invocation.getProxy().getAction());System.out.println(invocation.getProxy().getActionName());emp_loginSystem.out.println(invocation.getProxy().getMethod());*/String actionName = invocation.getProxy().getAction().getClass().getName();String methodName = invocation.getProxy().getMethod();String allName = actionName+"."+methodName;if("org.sihai.qualitycontrol.auth.emp.web.EmpAction.login".equals(allName)){return invocation.invoke();}//解决登录嵌套的问题//System.out.println(invocation.getProxy().getActionName()+"---"+invocation.getProxy().getAction().getClass().getName());if(invocation.getProxy().getActionName().equals("page_login")){return invocation.invoke();}//获取当前登录人信息EmpModel loginEm = (EmpModel) ActionContext.getContext().getSession().get(EmpModel.EMP_LOGIN_USER_OBJECT_NAME);//如果当前没有登录,跳转到登录页面if(loginEm == null){//跳转到登录return "noLogin";}//执行原始操作return invocation.invoke();}}
这里需要判断三个问题:
1、如果是登录方法,放行。
2、解决登录嵌套的问题
3、获取当前登录人的信息,判断是否有权限
2.2、拦截器配置
<interceptors><interceptor name="loginInterceptor" class="org.sihai.qualitycontrol.util.interceptor.LoginInterceptor"/><interceptor-stack name="systemStack"><interceptor-ref name="loginInterceptor"/><interceptor-ref name="defaultStack"/></interceptor-stack></interceptors><default-interceptor-ref name="systemStack"/>
这样就可以拦截非法的用户了。