1.建立一個攔截器類,繼承MethodFilterInterceptor類,實現doIntercept方法java
package com.yqg.bos.web.interceptor; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor; import com.yqg.bos.entity.User; import com.yqg.bos.utils.CommonUtils; public class BosInterceptor extends MethodFilterInterceptor{ //該攔截器功能爲若是session中的用戶爲空,跳轉到登陸界面。 protected String doIntercept(ActionInvocation invocation) throws Exception { User user = CommonUtils.getLoginUser(); if(user == null) {
//若是user爲空,跳回login.jsp界面,不然放行 return "login"; }else { return invocation.invoke(); } } }
package com.yqg.bos.utils; import javax.servlet.http.HttpSession; import org.apache.struts2.ServletActionContext; import com.yqg.bos.entity.User; public class CommonUtils { public static HttpSession getSession() { return ServletActionContext.getRequest().getSession(); } public static User getLoginUser() { return (User) getSession().getAttribute("loginUser"); } }
2.在struts.xml中配置該攔截器,並設置一個自定義攔截器棧做爲默認攔截器棧。web
<interceptors>
<!--將自定義的攔截器註冊到struts中--> <interceptor name="bosInterceptor" class="com.yqg.bos.web.interceptor.BosInterceptor">
<!--除login方法以外的全部方法都被攔截--> <param name = "excludeMethods">login</param> </interceptor>
<!--自定義攔截器棧,並將自定義攔截器加入到棧中,還將struts默認的攔截器棧加入到自定義攔截器棧中--> <interceptor-stack name="myStack"> <interceptor-ref name="bosInterceptor"></interceptor-ref> <interceptor-ref name="defaultStack"></interceptor-ref> </interceptor-stack> </interceptors>
<!--設置自定義攔截器棧爲默認攔截器棧取代struts的默認攔截器棧defaultStack--> <default-interceptor-ref name="myStack" /> <!--定義攔截結果--> <global-results> <result name="login">/login.jsp</result> </global-results>