本文研究的主要是Struts攔截器實現攔截未登陸用戶,具體實現如下。
首先建立一個工具類:
checkPrivilegeInterceptor:這個類繼承interceptor,這是一個接口,要實現三個方法,要是覺得比較多的話,可以繼承他的實現類AbstractInterceptor,繼承這個類以后只需要重寫一個方法,就是在這個方法里面控制,是否登錄,登錄以后有哪些權限,等等,代碼如下;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
package com.cjdx.utils; import javax.annotation.Resource; import org.hibernate.Session; import org.hibernate.SessionFactory; import com.cjdx.domain.User; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; //檢查是否有權限,這里只檢查知否登錄 public class CheckPrivilegeInterceptor extends AbstractInterceptor { @Override public String intercept(ActionInvocation invocation) throws Exception { User user = (User) ActionContext.getContext().getSession().get( "user" ); String nameSpace = invocation.getProxy().getNamespace(); String actionName = invocation.getProxy().getActionName(); String privilegeUrl = nameSpace + actionName; if (user == null ) { // 如果用戶沒有登錄 if (privilegeUrl.startsWith( "/user_login" )) { //如果用戶準備去登錄,則放行 return invocation.invoke(); } { return "loginUI" ; //如果用戶不是去登錄,又沒有登錄,則轉到登錄頁面 } } else { return invocation.invoke(); //如果用戶已經登錄,則執行相應的方法 } } } |
然后再配置struts2.xml里:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
<!-- 登錄攔截器的聲明 --> < interceptors > <!-- 聲明你已經寫好的攔截器 --> < interceptor name = "checkPrivilege" class = "com.cjdx.utils.CheckPrivilegeInterceptor" ></ interceptor > <!-- 將已經聲明的攔截器加到默認的攔截器里面去 --> <!-- 這個攔截器的名字就叫做defaultStack,這樣就直接覆蓋了原來的defaultStack --> <!-- 如果不這樣寫,還可以在像注釋這樣添加 --> < interceptor-stack name = "defaultStack" > < interceptor-ref name = "checkPrivilege" ></ interceptor-ref > < interceptor-ref name = "defaultStack" ></ interceptor-ref > </ interceptor-stack > <!-- <interceptor-stack name="myStack"> <interceptor-ref name="checkPrivilege"></interceptor-ref> <interceptor-ref name="defaultStack"></interceptor-ref> </interceptor-stack> <interceptor-stack name="defaultStack"> <interceptor-ref name="myStack"></interceptor-ref> </interceptor-stack> --> </ interceptors > |
總結
以上就是本文關于Struts攔截器實現攔截未登陸用戶實例解析的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
原文鏈接:http://blog.csdn.net/qq_28483283/article/details/50950400