工具類
public class BosUtils {
//獲取session
public static HttpSession getSession() {
return ServletActionContext.getRequest().getSession();
}
//獲取登錄用戶對象
public static User getLoginUser() {
return (User) getSession().getAttribute("loginUser");
}
}
自定義攔截器代碼:
繼承MethodFilterInterceptor:因爲在該類中有excludeMethodes方法,可以設置攔截哪些方法
public class BosLoginInterceptor extends MethodFilterInterceptor {
@Override
protected String doIntercept(ActionInvocation invocation) throws Exception {
// TODO Auto-generated method stub
//首先從session域中獲取登錄對象
//User user = (User) ServletActionContext.getRequest().getSession().getAttribute("loginUser");
User user = BosUtils.getLoginUser();
if(user == null) {
//未登錄用戶
return "login";
}
//放行
return invocation.invoke();
}
}
<!-- 配置自定義的攔截器
1.首先在Interceptor包中自定義攔截器
2.然後再struts.xml中配置攔截器,註解攔截器
3.自定義攔截器棧,添加自己定義的攔截器,以及將struts中默認的攔截器棧,添加進來
4.定義程序中使用的默認攔截器棧,即把自己定義的攔截器棧設置成默認的攔截器棧
-->
<interceptors>
<!-- 註解自定義攔截器 -->
<interceptor name="bosLoginInterceptor" class="com.itwx.bos.web.interceptor.BosLoginInterceptor">
<!-- 指定哪些方法不需要被攔截 -->
<param name="excludeMethods">login</param>
</interceptor>
<!-- 定義攔截器棧 -->
<interceptor-stack name="myStack">
<interceptor-ref name="bosLoginInterceptor"></interceptor-ref>
<!-- struts默認攔截器棧 (因爲在程序中需要使用自己定義的攔截器棧,所以把struts默認的添加進來)-->
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
</interceptors>
<!-- 定義默認(自己定義的)攔截器棧 -->
<default-interceptor-ref name="myStack"/>