首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

Struts登记自定义全局拦截器

2012-08-25 
Struts注册自定义全局拦截器当需要在项目的每次的action请求时,都希望执行指定的检测,可以使用Struts提供

Struts注册自定义全局拦截器
当需要在项目的每次的action请求时,都希望执行指定的检测,可以使用Struts提供的Interceptor实现,定义自定义拦截器,可以继承AbstractInterceptor这个类。如

public class SessionTimeoutInterceptor extends AbstractInterceptor{@Overridepublic 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"/>

热点排行