今天發現在用SessionFilter過濾session時發現servletResponse.sendRedirect(path+"/login.jsp");有時并不能跳轉,可改用攔截器實作。
在struts.xml中增加:
Java代碼
- <!-- 定義一個author攔截器,并定義一個預設攔截器 -->
- <interceptors>
- <interceptor name="authorLogin" class="com.rating.joyintech.action.AuthorizationInterceptor"/>
- <interceptor-stack name="myStack">
- <interceptor-ref name="defaultStack"/>
- <interceptor-ref name="authorLogin"/>
- </interceptor-stack>
- </interceptors>
- <default-interceptor-ref name="myStack"/>
- <global-results>
- <result name="noSession">/login.jsp</result>
- </global-results>
對應的攔截器代碼如下:
Java代碼
- package com.rating.joyintech.action;
- import java.util.Map;
- import javax.servlet.http.HttpServletRequest;
- import org.apache.struts2.ServletActionContext;
- import com.opensymphony.xwork2.ActionInvocation;
- import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
- public class AuthorizationInterceptor extends AbstractInterceptor{
- @Override
- public String intercept(ActionInvocation ai) throws Exception {
- // TODO Auto-generated method stub
- Map session = ai.getInvocationContext().getSession();
- HttpServletRequest request = ServletActionContext.getRequest();
- if(session.get("userInfo")==null && request.getRequestURI().indexOf("login")==-1){//login.action不攔截
- return "noSession";
- }else{
- return ai.invoke();
- }
- }
- }
轉載自:http://corejava5.iteye.com/blog/1213725