sturts2拦截器的使用实例

来源:互联网 发布:织梦cms内容管理系统 编辑:程序博客网 时间:2024/06/06 16:44

自定义一个类,继承MethodFilterInterceptor类,实现doIntercept方法

public class LoginInterceptor extends MethodFilterInterceptor{@Overrideprotected String doIntercept(ActionInvocation action) throws Exception {// TODO Auto-generated method stub//获取sessionMap<String, Object> map=ActionContext.getContext().getSession();//判断是否登录if(map.get("isLogin")!=null){//放行return action.invoke();}else{//返回登录页面return "login";}}}

通过struts2的配置文件把定义的类定义成默认拦截器

<!-- 配置自定义拦截器 --><interceptors><!-- 设置拦截器 -->  <interceptor name="myInterceptor" class="com.entor.interceptor.LoginInterceptor"></interceptor>  <interceptor-stack name="myDefaultInterceptor">  <interceptor-ref name="basicStack"></interceptor-ref>  <interceptor-ref name="myInterceptor">  <!-- 设置要拦截的方法,多个用逗号隔开 -->  <param name="includeMethods">add</param>  </interceptor-ref>  </interceptor-stack></interceptors> <!-- 把自定义拦截器定义成默认拦截器 --><default-interceptor-ref name="myDefaultInterceptor"></default-interceptor-ref>