public class SessionTimeoutInterceptor extends AbstractInterceptor{ @Override public String intercept(ActionInvocation actionInvocation) throws Exception { Map session = actionInvocation.getInvocationContext().getSession(); if (session.get("SPRING_SECURITY_CONTEXT")==null) { outString("{timeout:true}"); return Action.NONE; }else { return actionInvocation.invoke(); } } public void outString(String str) { HttpServletResponse response = ServletActionContext.getResponse(); try { response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("text/html;charset=gbk"); PrintWriter out = response.getWriter(); out.write(str); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } }
上面的代码是在每次经过action请求时,检查当前session是否已经过期,当过期时就向客户端输出session timeout的信息,并不执行该action请求。
把这个拦截器应用到项目中,需要在Struts.xml文件中配置,如
<interceptors> <interceptor name="timeoutInterceptor" class="com.edward.SessionTimeoutInterceptor"></interceptor> <interceptor-stack name="timeoutStack"> <interceptor-ref name="defaultStack"/> <interceptor-ref name="timeoutInterceptor"/> </interceptor-stack> </interceptors> <default-interceptor-ref name="timeoutStack"/>