Java三大器(2)-拦截器

这节我们来看看Java中重要的知识点-拦截器

拦截器的使用

先来看看拦截器的是怎样使用的

第一步 定义拦截器类,该类实现HandlerInterceptor接口

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class MyInterceptor implements HandlerInterceptor {

    /**
     * 该方法实在执行执行servlet的 service方法之前执行的
     * 即在进入controller之前调用
     * @return 如果返回true表示继续执行下一个拦截器的PreHandle方法;如果没有拦截器了,则执行controller
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
        String url = request.getRequestURI();
        System.out.println("进入Controller之前");
        if(url.indexOf("login") >= 0){
            return true;
        }

        String username = request.getParameter("username");
        if(username == null){
            return false;
        }

        return true;
    }

    /**
     *在执行完controller之后,返回视图之前执行,我们可以对controller返回的结果做处理
     * 执行顺序:先执行最后一个拦截器的postHandle方法,一次向前
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception{

        System.out.println("解析视图之前.....");
    }

    /**
     * 整个请求结束之后,即返回视图之后执行
     *该方法需要同一拦截器的preHandle返回true时执行,
     * 如果该拦截器preHandle返回false,则该拦截器的afterCompletion不执行
     * 执行顺序:先执行最后一个返回true的拦截器的afterCompletion,在依次向前
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                      Exception ex) throws Exception{
        System.out.println("视图解析完成...");
    }
}

Springboot环境中配置拦截器:

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    @Autowired
    private MyInterceptor interceptor;

    public void addInterceptors(InterceptorRegistry registry) {
        //addPathPatterns指定拦截器要拦截的路径
        //excludePathPatterns指定拦截器不拦截的路径
        registry.addInterceptor(interceptor).addPathPatterns("/**").excludePathPatterns("/logout");
    }
}

Spring MVC环境中配置拦截器:

  
   
      
        
        
       
         
        
      
 
上面两种选一种即可

编写Controller测试:

@RestController
public class LoginController {

    @RequestMapping("/login")
    public String intercept(){
        System.out.println("Controller执行中....");
        return "Hello Interceptor!";
    }

    @RequestMapping("/logout")
    public String logout(){
        System.out.println("注销中....");
        return "logouting.....!";
    }
}

先访问login,测试结果如下:

进入Controller之前
Controller执行中....
解析视图之前.....
视图解析完成...

在访问logout,

注销中....
发现并没有拦截

以上就是拦截器的使用,接下来通过源码看看拦截器到底如何起作用

源码分析

通过图来看看org.springframework.web.servlet.DispatcherServlet入口类的执行顺序。

先看看DispatcherServlet继承结构:


DispatcherServlet继承抽象类FrameworkServlet。再来看看请求进入DispatcherServlet后的执行顺序:

Java三大器(2)-拦截器_第1张图片

所以重点是doDispatch方法,方法源码如下:

 protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
	HttpServletRequest processedRequest = request;
	HandlerExecutionChain mappedHandler = null;
	boolean multipartRequestParsed = false;
	WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);

	try {
		try {
			ModelAndView mv = null;
			Object dispatchException = null;

			try {
				processedRequest = this.checkMultipart(request);
				multipartRequestParsed = processedRequest != request;
				//方法内部调用HandlerMapping的getHandler(request)方法获取HandlerExecutionChain 
				//如果请求的路径不存在,即不存在对应的handlerMapping,则返回null
				mappedHandler = this.getHandler(processedRequest);
				if (mappedHandler == null) {
					this.noHandlerFound(processedRequest, response);
					return;
				}

				HandlerAdapter ha = this.getHandlerAdapter(mappedHandler.getHandler());返回匹配该handler的handlerAdapter
				String method = request.getMethod();
				boolean isGet = "GET".equals(method);
				if (isGet || "HEAD".equals(method)) {
					long lastModified = ha.getLastModified(request, mappedHandler.getHandler());
					if (this.logger.isDebugEnabled()) {
						this.logger.debug("Last-Modified value for [" + getRequestUri(request) + "] is: " + lastModified);
					}

					if ((new ServletWebRequest(request, response)).checkNotModified(lastModified) && isGet) {
						return;
					}
				}

				//此处是关键,开始执行拦截器
				if (!mappedHandler.applyPreHandle(processedRequest, response)) {
					return;
				}

				mv = ha.handle(processedRequest, response, mappedHandler.getHandler());//从此处进入controller
				if (asyncManager.isConcurrentHandlingStarted()) {
					return;
				}

				this.applyDefaultViewName(processedRequest, mv);
				//内部执行拦截器的postHandle方法
				mappedHandler.applyPostHandle(processedRequest, response, mv);
			} catch (Exception var20) {
				dispatchException = var20;
			} catch (Throwable var21) {
				dispatchException = new NestedServletException("Handler dispatch failed", var21);
			}

			//方法内部先丢用render()方法解析视图,再调用applyPostHandle方法
			this.processDispatchResult(processedRequest, response, mappedHandler, mv, (Exception)dispatchException);
		} catch (Exception var22) {
			this.triggerAfterCompletion(processedRequest, response, mappedHandler, var22);//抛了异常也会执行拦截器的afterCompletion方法
		} catch (Throwable var23) {
			this.triggerAfterCompletion(processedRequest, response, mappedHandler, new NestedServletException("Handler processing failed", var23));
		}

	} finally {
		if (asyncManager.isConcurrentHandlingStarted()) {
			if (mappedHandler != null) {
				mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);
			}
		} else if (multipartRequestParsed) {
			this.cleanupMultipart(processedRequest);
		}

	}
}

mappedHandler.applyPreHandle(processedRequest, response)内部源码:

boolean applyPreHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HandlerInterceptor[] interceptors = this.getInterceptors();
        if (!ObjectUtils.isEmpty(interceptors)) {
            for(int i = 0; i < interceptors.length; this.interceptorIndex = i++) {
                HandlerInterceptor interceptor = interceptors[i];
		//执行拦截器的preHandle方法,而且是从头到尾执行每个拦截器的preHandle方法
                if (!interceptor.preHandle(request, response, this.handler)) {
		    //拦截器返回false
                    this.triggerAfterCompletion(request, response, (Exception)null);//
                    return false;
                }
            }
        }

        return true;
    }

mappedHandler.applyPostHandle(processedRequest, response, mv)内部源码:

void applyPostHandle(HttpServletRequest request, HttpServletResponse response, @Nullable ModelAndView mv) throws Exception {
        HandlerInterceptor[] interceptors = this.getInterceptors();
        if (!ObjectUtils.isEmpty(interceptors)) {
            for(int i = interceptors.length - 1; i >= 0; --i) {
		//倒序执行拦截器的postHandle方法
                HandlerInterceptor interceptor = interceptors[i];
                interceptor.postHandle(request, response, this.handler, mv);
            }
        }

    }

mappedHandler.triggerAfterCompletion(request, response, ex)内部源码:

void triggerAfterCompletion(HttpServletRequest request, HttpServletResponse response, @Nullable Exception ex) throws Exception {
        HandlerInterceptor[] interceptors = this.getInterceptors();
        if (!ObjectUtils.isEmpty(interceptors)) {
            for(int i = this.interceptorIndex; i >= 0; --i) {
                HandlerInterceptor interceptor = interceptors[i];

                try {
		    //倒序的执行每个拦截器的afterCompletion方法
                    interceptor.afterCompletion(request, response, this.handler, ex);
                } catch (Throwable var8) {
                    logger.error("HandlerInterceptor.afterCompletion threw exception", var8);
                }
            }
        }

    }
到此执行结束......



你可能感兴趣的:(Java)