【struts2+hibernate+spring项目实战】用户登录校验(struts拦截器)
生活随笔
收集整理的這篇文章主要介紹了
【struts2+hibernate+spring项目实战】用户登录校验(struts拦截器)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
一、概述
項目中所有頁面均放入WEB-INF,所有頁面安全性得到了很大程度的提高。但是當(dāng)用戶登錄后長時間沒有操作時,會造成Session數(shù)據(jù)的過期,如果此時獲取Session中的數(shù)據(jù),必定會引發(fā)WEB引用的空指針異常,造成數(shù)據(jù)錯誤,程序崩潰。因此需要一種機制保障每次發(fā)送請求執(zhí)行Action中的方法之前校驗用戶是否處于登錄狀態(tài)。
針對上述分析,可以選用兩種實現(xiàn)方式。
AOP
AOP思想可以在任意方法執(zhí)行前進行攔截,完成原始方法執(zhí)行前的操作
Struts2攔截器
Struts2攔截器可以再Struts2的任意Action執(zhí)行之前和之后,完成某些任務(wù),其內(nèi)部工作原理與AOP極其相似。
二、攔截器實現(xiàn)
2.1、攔截器實現(xiàn)類
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 {//執(zhí)行除了登錄操作之前的所有操作做登錄校驗//獲取本次操作的信息/*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();}//獲取當(dāng)前登錄人信息EmpModel loginEm = (EmpModel) ActionContext.getContext().getSession().get(EmpModel.EMP_LOGIN_USER_OBJECT_NAME);//如果當(dāng)前沒有登錄,跳轉(zhuǎn)到登錄頁面if(loginEm == null){//跳轉(zhuǎn)到登錄return "noLogin";}//執(zhí)行原始操作return invocation.invoke();}}這里需要判斷三個問題:
1、如果是登錄方法,放行。
2、解決登錄嵌套的問題
3、獲取當(dāng)前登錄人的信息,判斷是否有權(quán)限
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"/>這樣就可以攔截非法的用戶了。
總結(jié)
以上是生活随笔為你收集整理的【struts2+hibernate+spring项目实战】用户登录校验(struts拦截器)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【struts2+hibernate+s
- 下一篇: 【struts2+hibernate+s