Struts注册自定义全局拦截器

当需要在项目的每次的action请求时,都希望执行指定的检测,可以使用Struts提供的Interceptor实现,定义自定义拦截器,可以继承AbstractInterceptor这个类。如
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"/>

猜你喜欢

转载自jeyke.iteye.com/blog/1039145