今天发现在用SessionFilter过滤session时发现servletResponse.sendRedirect(path+"/login.jsp");有时并不能跳转,可改用拦截器实现。
在struts.xml中增加:
Java代码
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIn5GcuIXY0N3Xu92Yp9CXzV2Zh1WavwVbvNmLllXZ0lmL1EmdhpWZy92Yvw1LcpDc0RHaiojIsJye.png)
- <!-- 定义一个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代码
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIn5GcuIXY0N3Xu92Yp9CXzV2Zh1WavwVbvNmLllXZ0lmL1EmdhpWZy92Yvw1LcpDc0RHaiojIsJye.png)
- 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