Struts2自定義攔截器案例:驗證使用者是否登入攔截器
阿新 • • 發佈:2018-11-10
Struts攔截器是struts最強大的功能之一,也是他的核心
它可以在Action前後做一些事情,比如使用者登入驗證,這裡主要針對使用者登入配置詳細說明
一 首先自定義一個使用者攔截類,必須實現Interceptor介面或者繼承他的實現類
因為我們是要攔截使用者登入的,這裡繼承MethodFilterInterceptor類,此類可以針對方法進行攔截或方向
struts2攔截器原理就是AOP(面向切面)程式設計
package com.raylu.intercepter; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor; import com.raylu.domain.User; /** * 自定義使用者攔截器 * 如果沒有登入,自動跳轉至登入頁面 * 如果已經登入,則放行 * 自定義攔截器必須實現Intercepter介面或繼承他的實現類 * @author RayLu * */ public class UserInterceptor extends MethodFilterInterceptor{ private static final long serialVersionUID = 1L; @Override protected String doIntercept(ActionInvocation arg0) throws Exception { User user = (User) ServletActionContext.getRequest().getSession().getAttribute("existUser"); if(user==null){ return "login"; } //如果使用者存在,則放行 return arg0.invoke(); } }
二,進行struts.xml配置攔截器,原則上哪個模組需要被攔截則在哪個模組進行配置
另外攔截器可以設定針對特定方法 放行,也就是不攔截,這裡設定針對login方法不進行攔截
自定義攔截器配置需要注意: 如果配置了自定義攔截器棧,則Struts2原有的攔截器棧會失效,此時需引入struts2原有的攔截器棧defaultStack;
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <package name="crm" namespace="/" extends="struts-default"> <!-- 配置自定義攔截器 --> <interceptors> <interceptor name="UserInterceptor" class="com.raylu.intercepter.UserInterceptor"></interceptor> <!-- 配置自定義攔截器棧 --> <interceptor-stack name="myStack"> <!-- 引入自定義攔截器 --> <interceptor-ref name="UserInterceptor"> <!--表示對login這個方法不攔截,重要。。 --> <param name="excludeMethods">login</param> </interceptor-ref> <!-- 使用自定義攔截器必須引入defaultStack,否則只有自己的攔截器生效 --> <interceptor-ref name="defaultStack"></interceptor-ref> </interceptor-stack> </interceptors> <!-- 配置全域性返回值 --> <global-results> <result name="success">/jsp/success.jsp</result> <result name="login">/login.htm</result> <result name="customerList">/jsp/customer/list.jsp</result> </global-results> <!-- User模組 --> <action name="user_*" class="com.raylu.web.UserAction" method="{1}"> <!-- User模組中加入myStack攔截器 --> <interceptor-ref name="myStack"></interceptor-ref> </action> <!-- Customer模組 --> <action name="customer_*" class="com.raylu.web.CustomerAction" method="{1}"> <!-- Customer模組中加入攔截器 --> <interceptor-ref name="myStack"></interceptor-ref> </action> </package> </struts>