Spring mvc 拦截器的简单使用

public class CommonInterceptor extends HandlerInterceptorAdapterimplements
        InitializingBean {
    static Log log = LogFactory.getLog(CommonInterceptor.class);

    public void afterPropertiesSet() throws Exception {
        log.debug("=======初始化CommonInterceptor拦截器=========");
    }

    @Override
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throwsException {
        log.debug("=====preHandle====");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        log.debug("==========postHandle=========");

        if (modelAndView != null) {
            String viewName = modelAndView.getViewName();
            log.debug("view name : " + viewName);
        } else {
            log.debug("view is null");
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest httpservletrequest,
            HttpServletResponse httpservletresponse, Object obj,

            Exception exception) throws Exception {
        log.debug("=====afterCompletion====");
    }
}

拦截器的四个方法的执行时间如下:

afterPropertiesSet():在系统启动时执行

preHandle():这个方法在业务处理器处理请求之前被调用,在该方法中对用户请求request进行处理。如果程序员决定该拦截器对请求进行拦截处理后还要调用其他的拦截器,或者是业务处理器去进行处理,则返回true;如果程序员决定不需要再调用其他的组件去处理请求,则返回false。

postHandle():这个方法在业务处理器处理完请求后,但是DispatcherServlet向客户端返回请求前被调用,在该方法中对用户请求request进行处理。

afterCompletion():这个方法在DispatcherServlet完全处理完请求后被调用,可以在该方法中进行一些资源清理的操作。

Xml配置如下

<property name="interceptors">
        <list>
            <bean class="com.interceptor.CommonInterceptor" />
        </list>
</property>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值