Struts2攔截器登錄驗證

Tomcat 索尼電腦娛樂 技術 科技優家 2017-05-08

Struts2攔截器

Struts2攔截器的概念和Spring Mvc攔截器一樣。

  1. Struts2攔截器是在訪問某個Action或Action的某個方法,字段之前或之後實施攔截,並且Struts2攔截器是可插拔的,攔截器是AOP的一種實現.
  2. 攔截器棧(Interceptor Stack)。Struts2攔截器棧就是將攔截器按一定的順序聯結成一條鏈。在訪問被攔截的方法或字段時,Struts2攔截器鏈中的攔截器就會按其之前定義的順序被調用。

使用攔截器的第一步:

自定義我的權限攔截器CheckPrivilegeInterceptor,這個攔截器繼承自AbstractInterceptor這個抽象類,當然你可以實現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元素節點下添加以下配置:

<!-- 配置攔截器 -->
        <interceptors>
 <!-- 聲明攔截器 -->
 <interceptor name="checkPrivilege" class="com.shizongger.oa.util.CheckPrivilegeInterceptor"></interceptor>
 
 <!-- 重新定義默認的攔截器棧 -->
 <interceptor-stack name="defaultStack">
 <interceptor-ref name="checkPrivilege"></interceptor-ref> 
 <interceptor-ref name="defaultStack"></interceptor-ref> 
 </interceptor-stack>
        </interceptors>

啟動我的Tomcat服務器,當我在瀏覽器輸入我的action地址時,都會被該攔截器的intercept攔截,默認是放行的,如果返回空字符串則因找不到對應的視圖而報錯。

登錄和權限攔截

攔截器在Web開發中應用場景最多的地方就是登錄驗證和權限驗證了。對於那些未登錄系統的用戶,一般我們都把他所有的請求打回到登錄頁面。而對於那些已經登錄系統的用戶,如果你不具有相應的權限,那麼將無法訪問我們的url。

首先在監聽器中最一些系統做一些監聽任務。

public class MyServletContextListener implements ServletContextListener {
    
    Log log = LogFactory.getLog(this.getClass);
    
    @Autowired
    private PrivilegeService privilegeService;
    
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        log.debug("---銷燬監聽器---");
    }

    @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;
        //將權限list放到比application作用域還大的ServletContext
        sc.setAttribute("topPrivilegeList", topPrivilegeList);
        
        // 準備數據:allPrivilegeUrls
        Collection<String> allPrivilegeUrls = privilegeService.getAllPrivilegeUrls;
        sc.setAttribute("allPrivilegeUrls", allPrivilegeUrls);      
    }
}

監聽器的任務是從Web容器中獲得Spring的容器ApplicationContext,再從ApplicationContext中獲得權限服務類privilegeService,這個service主要作用有兩點,其一是獲得有多的頂級權限列表;其二是獲得所以權限列表。將這兩者放入到application裡邊。

接下來就可以在我們的攔截器中寫登錄攔截的邏輯代碼了。

    public String intercept(ActionInvocation invocation) throws Exception {     
        //獲取信息,從session中取出當前登錄用戶
        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("/user_login".equals(privilegeUrl)) {
 return invocation.invoke;
 //否則跳轉到登錄頁面
 } else {
 return "loginUI";
 }
        } else {
 //如果已經登錄則判斷是否有權限
 if(user.hasPrivilegeByUrl(privilegeUrl)) {
 return invocation.invoke;
 } else {
 return "noPrivilegeError";
 }
        }
    }

處理的邏輯是,如果未登錄,則判斷是不是要去登錄,如果用戶正在登錄則放行,其他請求都要跳轉到loginUI登錄頁面。如果已經登錄,則判斷正在登錄的用戶是否具有相對應的權限。而判斷是否具有權限的方法在我的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方法
    
    /**
     * 判斷用戶是否用該權限
     * @param privilegename 權限名稱
     * @return
     */
    public boolean hasPrivilegeByName(String privilegeName) {
        log.debug("權限名稱:" + privilegeName);
        
        //從本用戶中取出所有角色
        for(Role role : roles) {
 //從角色遍歷出所有權限
 Set<Privilege> privilegeList = role.getPrivileges;
 for(Privilege privilege : privilegeList) {
 if(privilegeName.equals(privilege.getName)) {
 log.debug(privilegeName + "---有權限---");
 return true;
 }
 }
        }
        
        log.debug(privilegeName + "---沒有權限---");
        return false;
    }
    
    /**
     * 判斷本用戶是否有指定URL的權限
     * 
     * @param privUrl
     * @return
     */
    public boolean hasPrivilegeByUrl(String privUrl) {
        // 超級管理有所有的權限
        if (isAdmin) {
 return true;
        }

        // >> 去掉後面的參數
        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 {
 // 普通用戶要判斷是否含有這個權限
 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方法為根據url判斷用戶是否具有權限的代碼邏輯,此邏輯分為三部分。其一,如果登錄的用戶是超級管理員admin,則不用驗證權限,該用戶具有所有的權限。其二,如果登錄的用戶基本功能部分不用驗證,需要驗證的功能才需要驗證。基礎功能模塊比如首頁,退出,登錄頁面等都不要再驗證。

權限的service實現類如下:

@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;
    }

}

未登錄的狀態直接輸入主頁面將自動彈回登錄頁面,如圖所示

Struts2攔截器登錄驗證

在登錄狀態下權限如圖:

Struts2攔截器登錄驗證

另:

  1. Spring Mvc攔截器請參考spring mvc攔截器
  2. 本項目的GitHub地址

相關推薦

推薦中...