zoukankan      html  css  js  c++  java
  • Spring MVC 拦截器

    Interceptor拦截器用于拦截Controller层接口,表现形式有点像Spring的AOP,但是AOP是针对单一的方法。Interceptor是针对Controller接口以及可以处理request和response对象。比如在没有登录的情况下,会拦截访问系统的请求,一般来说拦截对象会除去登录页面以及静态文件。配置代码如下:

    <mvc:interceptor>
                <mvc:mapping path="/**"/>
                <mvc:exclude-mapping path="/login/**"/>
                <mvc:exclude-mapping path="/css/**"/>
                <mvc:exclude-mapping path="/js/**"/>
                <mvc:exclude-mapping path="/images/**"/>
                <mvc:exclude-mapping path="/api/**"/>
                <bean class="org.imooc.controller.interceptor.SessionInterceptor"></bean>
     </mvc:interceptor>

    HandlerInterceptor接口定义了三个方法,分别是preHandle、postHandle、afterCompletion:

    public interface HandlerInterceptor {
    
        boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
                throws Exception;
    
        void postHandle(
                HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
                throws Exception;
    
        void afterCompletion(
                HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
                throws Exception;
    
    }

    preHandle在进入Controller之前被调用,当preHandle返回true会执行下一个拦截器,当所有拦截器执行完再调用被拦截的Controller;当preHandle返回false会往回执行所有拦截器的afterCompletion,再退出拦截器链

    postHandle是调用Controller之后被调用,但是在渲染View页面之前。

    afterCompletion是调用完Controller接口,渲染View页面最后调用。返回true的拦截器都会调用该拦截器的afterCompletion方法,顺序相反。

  • 相关阅读:
    sh执行脚本报错Syntax error: "(" unexpected
    Ubuntu源码编译安装PostgreSQL
    Linux解决Graphical installers are not supported by the VM
    pytest功能入门
    vscode配置远程开发环境失败_workbench.downloadResource
    花生壳新版 内网穿透教程
    同局域网内进行本机调试
    Windows10激活
    win server 2012安装Vmware tools
    windows实现超级隐藏用户
  • 原文地址:https://www.cnblogs.com/johnnytoo/p/10029764.html
Copyright © 2011-2022 走看看