十一、springboot WebMvcConfigurer与HandlerInterceptorAdapter使用

springboot WebMvcConfigurer与HandlerInterceptorAdapter使用

简介

WebMvcConfigurer:拦截器的注册类
HandlerInterceptorAdapter:拦截组件

拦截组件HandlerInterceptorAdapter可以有多个,需要注册到WebMvcConfigurer里面,在WebMvcConfigurer里面拦截器是按顺序执行的。

  • 在Spring Boot 2.0后都是靠重写WebMvcConfigurer的方法来添加自定义拦截器,消息转换器等。
  • 在SpringBoot2.0及Spring 5.0前,该类WebMvcConfigurerAdapter被标记为@Deprecated,已被废弃。

WebMvcConfigurer的作用

修饰符和类型 方法 描述
default void addArgumentResolvers(java.util.List resolvers) 添加解析器以支持自定义控制器方法参数类型。
default void addCorsMappings(CorsRegistry registry) 配置跨源请求处理。
default void addFormatters(FormatterRegistry registry) 添加Converters和Formatters除了默认注册的那些。
default void addInterceptors(InterceptorRegistry registry) 添加Spring MVC生命周期拦截器,用于控制器方法调用的预处理和后处理。
default void addResourceHandlers(ResourceHandlerRegistry registry) 添加处理程序以提供静态资源,例如来自Web应用程序根目录下的特定位置的图像,js和css文件,类路径等。
default void addReturnValueHandlers(java.util.List handlers) 添加处理程序以支持自定义控制器方法返回值类型。
default void addViewControllers(ViewControllerRegistry registry) 配置预配置了响应状态代码的简单自动控制器和/或视图以呈现响应主体。
default void configureAsyncSupport(AsyncSupportConfigurer configurer) 配置异步请求处理选项。
default void configureContentNegotiation(ContentNegotiationConfigurer configurer) 配置内容协商选项。
default void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) 配置处理程序以通过转发到Servlet容器的“默认”servlet来委派未处理的请求。
default void configureHandlerExceptionResolvers(java.util.List resolvers) 配置异常解析器。
default void configureMessageConverters(java.util.List<HttpMessageConverter<?>> converters) 配置HttpMessageConverters用于读取或写入请求或响应的正文。
default void configurePathMatch(PathMatchConfigurer configurer) 帮助配置HandlerMappings路径匹配选项,例如尾部斜杠匹配,后缀注册,路径匹配器和路径助手。
default void configureViewResolvers(ViewResolverRegistry registry) 配置视图解析器以将从控制器返回的基于字符串的视图名称转换为具体View 实现以执行渲染。
default void extendHandlerExceptionResolvers(java.util.List resolvers) 扩展或修改默认配置的异常解析器列表。
default void extendMessageConverters(java.util.List<HttpMessageConverter<?>> converters) 用于在配置转换器列表后扩展或修改转换器列表的挂钩。
default MessageCodesResolver getMessageCodesResolver() 提供MessageCodesResolver用于根据数据绑定和验证错误代码构建消息代码的自定义。
default Validator getValidator() 提供自定义Validator而不是默认创建的自定义。

准备工作

1.创建一个WebMvcConfig类

package com.honghh.bootfirst.config;


import com.honghh.bootfirst.interceptor.AccessSignAuthInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;

/**
 * MVC配置
 *
 * @author honghh
 * @date 2018/8/7 23:01
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Resource
    private AccessSignAuthInterceptor accessSignAuthInterceptor;

    /**
     * Description :
     * Group :
     * <p>
     * 实现自定义拦截器只需要3步
     * 1、创建我们自己的拦截器类并实现 HandlerInterceptor 接口。
     * 2、创建一个Java类继承WebMvcConfigurerAdapter,并重写 addInterceptors 方法。
     * 3、实例化我们自定义的拦截器,然后将对像手动添加到拦截器链中(在addInterceptors方法中添加)。
     *
     * @param registry
     * @author honghh
     * @date 2019/3/22 0022 10:08
     * @author honghh
     * @date 2018/8/13 13:56
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        InterceptorRegistration registration = registry.addInterceptor(accessSignAuthInterceptor);
        // 拦截配置
        registration.addPathPatterns("/api/**");
        // 排除配置
        registration.excludePathPatterns("/api/word");
    }
}

2.创建一个ApiController

package com.honghh.bootfirst.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * ClassName: ApiController
 * Description:
 *
 * @author honghh
 * @date 2019/03/22 9:36
 */
@RestController
@RequestMapping("api")
public class ApiController {

    @RequestMapping("hello")
    public String hello() {
        return "Hello Spring Boot!";
    }

    @RequestMapping("word")
    public String word() {
        return "Hello word!";
    }
}

3.定义一个AccessSignAuthInterceptor类

package com.honghh.bootfirst.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

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

/**
 * description:
 *
 * @author: hh
 * @date: 2018/8/13 11:03
 */
@Slf4j
@Component
public class AccessSignAuthInterceptor extends HandlerInterceptorAdapter {

    /**
     * 只有返回true才会继续向下执行,返回false取消当前请求
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     * @author honghh
     * @date 2018/8/13 13:58
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("preHandle:请求前调用");
        String url = request.getRequestURI();
        log.info("请求url:{}",url);
        //返回 false 则请求中断
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        log.info("postHandle:请求后调用");
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        log.info("afterCompletion:请求调用完成后回调方法,即在视图渲染完成后回调");
    }
}

4.启动项目分别对api/hello,api/word发起请求

返回结果

该项目是基于上一节 十、springboot注解式AOP(@Aspect)统一日志管理 实现。主要添加了以上几个类,获取源码增加上即可。

代码获取

https://gitee.com/honghh/boot-demo.git [boot-aspect]

参考文献

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/config/annotation/WebMvcConfigurer.html

发布了58 篇原创文章 · 获赞 64 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/qq_35098526/article/details/88734991