SpringBoot 很重要的一个类WebMvcConfigurerAdapter 的使用

自定义资源映射addResourceHandlers

比如,我们想自定义静态资源映射目录的话,只需重写addResourceHandlers方法即可。

@Configuration
public class MyWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {
    /**
     * 配置静态访问资源
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/my/**").addResourceLocations("classpath:/my/");
        super.addResourceHandlers(registry);
    }
}

通过addResourceHandler添加映射路径,然后通过addResourceLocations来指定路径。我们访问自定义my文件夹中的elephant.jpg 图片的地址为 http://localhost:8080/my/elephant.jpg

如果你想指定外部的目录也很简单,直接addResourceLocations指定即可,代码如下:

@Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/my/**").addResourceLocations("file:E:/my/");
        super.addResourceHandlers(registry);
    }

addResourceLocations指的是文件放置的目录,addResoureHandler指的是对外暴露的访问路径

配置拦截器

在之前Xml配置形式天下的时候,我们都是在spring-mvc.xml配置文件内添加<mvc:interceptor>标签配置拦截器。拦截器的相关创建请访问第六章:如何在SpringBoot项目中使用拦截器,拦截器配置如下所示:

    /**
     * 拦截器配置
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        super.addInterceptors(registry);
        registry.addInterceptor(new TestInterceptor()).addPathPatterns("/**");
    }

InterceptorRegistry 内的addInterceptor需要一个实现HandlerInterceptor接口的拦截器实例,addPathPatterns方法用于设置拦截器的过滤路径规则。

拦截器addInterceptors

拦截器在我们项目中经常使用的,这里就来介绍下最简单的判断是否登录的使用。
要实现拦截器功能需要完成以下2个步骤:

  • 创建我们自己的拦截器类并实现 HandlerInterceptor 接口
  • 其实重写WebMvcConfigurerAdapter中的addInterceptors方法把自定义的拦截器类添加进来即可

首先,自定义拦截器代码:

package com.dudu.interceptor;
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean flag =true;
        User user=(User)request.getSession().getAttribute("user");
        if(null==user){
            response.sendRedirect("toLogin");
            flag = false;
        }else{
            flag = true;
        }
        return flag;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}

这里我们简单实现了根据session中是否有User对象来判断是否登录,为空就跳转到登录页,不为空就通过。

接着,重写WebMvcConfigurerAdapter中的addInterceptors方法如下:

/**
* 拦截器
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
    // addPathPatterns 用于添加拦截规则
    // excludePathPatterns 用户排除拦截
    registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**").excludePathPatterns("/toLogin","/login");
    super.addInterceptors(registry);
}

addPathPatterns("/**")对所有请求都拦截,但是排除了/toLogin/login请求的拦截。

配置CORS

跨域我们之前章节也有讲到,请访问第二十五章:SpringBoot添加支持CORS跨域访问Spring既然为了集成了CORS,那就证明了一点,以后前后端分离是一个开发趋势,配置代码如下所示:

    /**
     * 跨域CORS配置
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        super.addCorsMappings(registry);
        registry.addMapping("/cors/**")
                .allowedHeaders("*")
                .allowedMethods("POST","GET")
                .allowedOrigins("*");
    }

配置ViewController

这一个配置在之前是经常被使用到的,最经常用到的就是"/"、"/index"路径请求时不通过@RequestMapping配置,而是直接通过配置文件映射指定请求路径到指定View页面,当然也是在请求目标页面时不需要做什么数据处理才可以这样使用,配置内容如下所示:

    /**
     * 视图控制器配置
     * @param registry
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        super.addViewControllers(registry);
        registry.addViewController("/").setViewName("/index");
    }

配置ViewResolver

这个对我们来说很熟悉,只要我们配置html、Jsp页面视图时就会用到InternalResourceViewResolver配置类,然后设置preffixsuffix参数进行配置视图文件路径前缀与后缀。配置代码如下所示:

    /**
     * 配置请求视图映射
     * @return
     */
    @Bean
    public InternalResourceViewResolver resourceViewResolver()
    {
        InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
        //请求视图文件的前缀地址
        internalResourceViewResolver.setPrefix("/WEB-INF/jsp/");
        //请求视图文件的后缀
        internalResourceViewResolver.setSuffix(".jsp");
        return internalResourceViewResolver;
    }
 
    /**
     * 视图配置
     * @param registry
     */
    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        super.configureViewResolvers(registry);
        registry.viewResolver(resourceViewResolver());
        /*registry.jsp("/WEB-INF/jsp/",".jsp");*/
    }

上述代码中方法resourceViewResolver上配置了@Bean注解,该注解会将方法返回值加入到SpringIoc容器内。
而在configureViewResolvers方法内配置视图映射为resourceViewResolver方法返回的InternalResourceViewResolver实例,这样完成了视图的配置。在下面还有注释掉的一部分代码,这块代码很神奇,我们先来看看org.springframework.web.servlet.config.annotation.ViewResolverRegistry源码:

package org.springframework.web.servlet.config.annotation;
 
public class ViewResolverRegistry {
    ...//省略代码
    public UrlBasedViewResolverRegistration jsp() {
        return this.jsp("/WEB-INF/", ".jsp");
    }
 
    public UrlBasedViewResolverRegistration jsp(String prefix, String suffix) {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix(prefix);
        resolver.setSuffix(suffix);
        this.viewResolvers.add(resolver);
        return new UrlBasedViewResolverRegistration(resolver);
    }
}
...//省略代码

配置MessageConverter

这个配置一般针对于Api接口服务程序,配置在请求返回时内容采用什么转换器进行转换,我们最常用到的就是fastJson的转换,配置如下所示:

/**
     * 消息内容转换配置
     * 配置fastJson返回json转换
     * @param converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        //调用父类的配置
        super.configureMessageConverters(converters);
        //创建fastJson消息转换器
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        //创建配置类
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        //修改配置返回内容的过滤
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.DisableCircularReferenceDetect,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty
        );
        fastConverter.setFastJsonConfig(fastJsonConfig);
        //将fastjson添加到视图消息转换器列表内
        converters.add(fastConverter);
    }

内容转换都是针对面向接口进行编写的实现类,都必须implements HttpMessageConverter接口完成方法的实现。

原文地址:https://www.cnblogs.com/ysq2018China/p/10212585.html