Struts2攔截器登錄驗證實例
Struts2攔截器
Struts2攔截器的概念和Spring Mvc攔截器一樣。
1.Struts2攔截器是在訪問某個Action或Action的某個方法,字段之前或之后實施攔截,并且Struts2攔截器是可插拔的,攔截器是AOP的一種實現(xiàn).
2.攔截器棧(Interceptor Stack)。Struts2攔截器棧就是將攔截器按一定的順序聯(lián)結(jié)成一條鏈。在訪問被攔截的方法或字段時,Struts2攔截器鏈中的攔截器就會按其之前定義的順序被調(diào)用。
使用攔截器的第一步:
自定義我的權(quán)限攔截器CheckPrivilegeInterceptor,這個攔截器繼承自AbstractInterceptor這個抽象類,當(dāng)然你可以實現(xiàn)Interceptor這個接口。
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.shizongger.oa.domain.User;
public class CheckPrivilegeInterceptor extends AbstractInterceptor {
@Override
public String intercept(ActionInvocation invocation) throws Exception {
System.out.println("---攔截器未攔截之前---");
String result = invocation.invoke();
System.out.println("---攔截器攔截之后---");
return result;
}
}
自定義的攔截器要覆蓋AbstractInterceptor抽象類的抽象方法intercept()方法,該方法是對所有的action進行攔截,String類型的返回值是我們將要返回的視圖,如果要放行我們要攔截的action地址,那么代碼如上所示。
使用攔截器的第二步:
配置struts的配置文件,主要是配置自定義的攔截器和配置攔截器棧。在struts.xml配置文件的package元素節(jié)點下添加以下配置:
<!-- 配置攔截器 -->
<interceptors>
<!-- 聲明攔截器 -->
<interceptor name="checkPrivilege" class="com.shizongger.oa.util.CheckPrivilegeInterceptor"></interceptor>
<!-- 重新定義默認(rèn)的攔截器棧 -->
<interceptor-stack name="defaultStack">
<interceptor-ref name="checkPrivilege"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
</interceptors>
啟動我的Tomcat服務(wù)器,當(dāng)我在瀏覽器輸入我的action地址時,都會被該攔截器的intercept攔截,默認(rèn)是放行的,如果返回空字符串則因找不到對應(yīng)的視圖而報錯。
登錄和權(quán)限攔截
攔截器在Web開發(fā)中應(yīng)用場景最多的地方就是登錄驗證和權(quán)限驗證了。對于那些未登錄系統(tǒng)的用戶,一般我們都把他所有的請求打回到登錄頁面。而對于那些已經(jīng)登錄系統(tǒng)的用戶,如果你不具有相應(yīng)的權(quán)限,那么將無法訪問我們的url。
首先在監(jiān)聽器中最一些系統(tǒng)做一些監(jiān)聽任務(wù)。
public class MyServletContextListener implements ServletContextListener {
Log log = LogFactory.getLog(this.getClass());
@Autowired
private PrivilegeService privilegeService;
@Override
public void contextDestroyed(ServletContextEvent sce) {
log.debug("---銷毀監(jiān)聽器---");
}
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext sc = sce.getServletContext();
ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sc);
PrivilegeService privilegeService = (PrivilegeService) ac.getBean("privilegeServiceImpl");
List<Privilege> topPrivilegeList = privilegeService.findTopList();
//將權(quán)限list放到比application作用域還大的ServletContext
sc.setAttribute("topPrivilegeList", topPrivilegeList);
// 準(zhǔn)備數(shù)據(jù):allPrivilegeUrls
Collection<String> allPrivilegeUrls = privilegeService.getAllPrivilegeUrls();
sc.setAttribute("allPrivilegeUrls", allPrivilegeUrls);
}
}
監(jiān)聽器的任務(wù)是從Web容器中獲得Spring的容器ApplicationContext,再從ApplicationContext中獲得權(quán)限服務(wù)類privilegeService,這個service主要作用有兩點,其一是獲得有多的頂級權(quán)限列表;其二是獲得所以權(quán)限列表。將這兩者放入到application里邊。
接下來就可以在我們的攔截器中寫登錄攔截的邏輯代碼了。
public String intercept(ActionInvocation invocation) throws Exception {
//獲取信息,從session中取出當(dāng)前登錄用戶
User user = (User) ActionContext.getContext().getSession().get("user");
String nameSpace = invocation.getProxy().getNamespace();
String actionName = invocation.getProxy().getActionName();
//對應(yīng)的權(quán)限地址
String privilegeUrl = nameSpace + actionName;
//如果未登錄
if(user == null) {
//如果是去登錄的頁面和登錄請求,就放行
if("/user_login".equals(privilegeUrl)) {
return invocation.invoke();
//否則跳轉(zhuǎn)到登錄頁面
} else {
return "loginUI";
}
} else {
//如果已經(jīng)登錄則判斷是否有權(quán)限
if(user.hasPrivilegeByUrl(privilegeUrl)) {
return invocation.invoke();
} else {
return "noPrivilegeError";
}
}
}
處理的邏輯是,如果未登錄,則判斷是不是要去登錄,如果用戶正在登錄則放行,其他請求都要跳轉(zhuǎn)到loginUI登錄頁面。如果已經(jīng)登錄,則判斷正在登錄的用戶是否具有相對應(yīng)的權(quán)限。而判斷是否具有權(quán)限的方法在我的user.java里面。
/**
* 用戶實體
* @author shizongger
* @date 2017/03/24
*/
public class User {
private Log log = LogFactory.getLog(this.getClass());
private Long id;
private String loginName;
private String password;
private String name;
private String gender;
private String phoneNumber;
private String email;
private String description;
private Department department;
private Set<Role> roles;
//getter/settter方法
/**
* 判斷用戶是否用該權(quán)限
* @param privilegename 權(quán)限名稱
* @return
*/
public boolean hasPrivilegeByName(String privilegeName) {
log.debug("權(quán)限名稱:" + privilegeName);
//從本用戶中取出所有角色
for(Role role : roles) {
//從角色遍歷出所有權(quán)限
Set<Privilege> privilegeList = role.getPrivileges();
for(Privilege privilege : privilegeList) {
if(privilegeName.equals(privilege.getName())) {
log.debug(privilegeName + "---有權(quán)限---");
return true;
}
}
}
log.debug(privilegeName + "---沒有權(quán)限---");
return false;
}
/**
* 判斷本用戶是否有指定URL的權(quán)限
*
* @param privUrl
* @return
*/
public boolean hasPrivilegeByUrl(String privUrl) {
// 超級管理有所有的權(quán)限
if (isAdmin()) {
return true;
}
// >> 去掉后面的參數(shù)
int pos = privUrl.indexOf("?");
if (pos > -1) {
privUrl = privUrl.substring(0, pos);
}
// >> 去掉UI后綴
if (privUrl.endsWith("UI")) {
privUrl = privUrl.substring(0, privUrl.length() - 2);
}
// 如果本URL不需要控制,則登錄用戶就可以使用
Collection<String> allPrivilegeUrls = (Collection<String>) ActionContext.getContext().getApplication().get("allPrivilegeUrls");
if (!allPrivilegeUrls.contains(privUrl)) {
return true;
} else {
// 普通用戶要判斷是否含有這個權(quán)限
for (Role role : roles) {
for (Privilege priv : role.getPrivileges()) {
if (privUrl.equals(priv.getUrl())) {
return true;
}
}
}
return false;
}
}
/**
* 判斷本用戶是否是超級管理員
*
* @return
*/
public boolean isAdmin() {
return "admin".equals(loginName);
}
}
hasPrivilegeByUrl()方法為根據(jù)url判斷用戶是否具有權(quán)限的代碼邏輯,此邏輯分為三部分。其一,如果登錄的用戶是超級管理員admin,則不用驗證權(quán)限,該用戶具有所有的權(quán)限。其二,如果登錄的用戶基本功能部分不用驗證,需要驗證的功能才需要驗證。基礎(chǔ)功能模塊比如首頁,退出,登錄頁面等都不要再驗證。
權(quán)限的service實現(xiàn)類如下:
@Service
public class PrivilegeServiceImpl extends DaoSupportImpl<Privilege> implements PrivilegeService {
@Override
@Transactional
public List<Privilege> findTopList() {
List<Privilege> topPrivletList = this.getSession()
.createQuery("FROM Privilege p WHERE p.parent IS NULL")
.list();
return topPrivletList;
}
@Override
@Transactional
public Collection<String> getAllPrivilegeUrls() {
return getSession().createQuery(//
"SELECT DISTINCT p.url FROM Privilege p WHERE p.url IS NOT NULL")//
.list();
}
}
未登錄的狀態(tài)直接輸入主頁面將自動彈回登錄頁面,如圖所示

在登錄狀態(tài)下權(quán)限如圖:

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
MyBatis動態(tài)SQL標(biāo)簽的用法詳解
這篇文章主要介紹了MyBatis動態(tài)SQL標(biāo)簽的用法詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04
SpringBoot詳解shiro過濾器與權(quán)限控制
當(dāng)shiro被運用到web項目時,shiro會自動創(chuàng)建一些默認(rèn)的過濾器對客戶端請求進行過濾。比如身份驗證、授權(quán)的相關(guān)的,這篇文章主要介紹了shiro過濾器與權(quán)限控制2022-07-07
Java數(shù)據(jù)結(jié)構(gòu)二叉樹難點解析
樹是一種重要的非線性數(shù)據(jù)結(jié)構(gòu),直觀地看,它是數(shù)據(jù)元素(在樹中稱為結(jié)點)按分支關(guān)系組織起來的結(jié)構(gòu),很象自然界中的樹那樣。樹結(jié)構(gòu)在客觀世界中廣泛存在,如人類社會的族譜和各種社會組織機構(gòu)都可用樹形象表示2021-10-10

