天天看點

struts2 session攔截器

今天發現在用SessionFilter過濾session時發現servletResponse.sendRedirect(path+"/login.jsp");有時并不能跳轉,可改用攔截器實作。

在struts.xml中增加:

Java代碼  

struts2 session攔截器
  1. <!-- 定義一個author攔截器,并定義一個預設攔截器 -->  
  2.     <interceptors>    
  3.            <interceptor name="authorLogin" class="com.rating.joyintech.action.AuthorizationInterceptor"/>  
  4.            <interceptor-stack name="myStack">    
  5.               <interceptor-ref name="defaultStack"/>    
  6.               <interceptor-ref name="authorLogin"/>    
  7.            </interceptor-stack>    
  8.        </interceptors>     
  9.        <default-interceptor-ref name="myStack"/>  
  10.        <global-results>   
  11.         <result name="noSession">/login.jsp</result>  
  12.     </global-results>  

對應的攔截器代碼如下:

Java代碼  

struts2 session攔截器
  1. package com.rating.joyintech.action;  
  2. import java.util.Map;  
  3. import javax.servlet.http.HttpServletRequest;  
  4. import org.apache.struts2.ServletActionContext;  
  5. import com.opensymphony.xwork2.ActionInvocation;  
  6. import com.opensymphony.xwork2.interceptor.AbstractInterceptor;  
  7. public class AuthorizationInterceptor extends AbstractInterceptor{  
  8.     @Override  
  9.     public String intercept(ActionInvocation ai) throws Exception {  
  10.         // TODO Auto-generated method stub  
  11.         Map session = ai.getInvocationContext().getSession();  
  12.         HttpServletRequest request = ServletActionContext.getRequest();  
  13.         if(session.get("userInfo")==null && request.getRequestURI().indexOf("login")==-1){//login.action不攔截  
  14.             return "noSession";  
  15.         }else{  
  16.             return ai.invoke();  
  17.         }  
  18.     }  

轉載自:http://corejava5.iteye.com/blog/1213725

繼續閱讀