zl程序教程

您现在的位置是:首页 >  Javascript

当前栏目

spring boot 中WebMvcConfigurer相关使用总结

2023-04-18 13:15:57 时间

本文为博主原创,未经允许不得转载:

  WebMvcConfigurer 为spring boot中的一个接口,用来配置web相关的属性或工具插件,比如消息转换器,拦截器,视图处理器,跨域设置等等。

  在Spring Boot 1.5版本都是靠重写WebMvcConfigurerAdapter的方法来添加自定义拦截器,消息转换器等。SpringBoot 2.0 后,该类被标记为@Deprecated(弃用)。

    官方推荐直接实现WebMvcConfigurer或者直接继承WebMvcConfigurationSupport,方式一实现WebMvcConfigurer接口(推荐),

    方式二继承WebMvcConfigurationSupport类,具体实现可看这篇文章。https://blog.csdn.net/fmwind/article/details/82832758

其中定义的方法如下,可以根据其中定义的方法,进行对应的封装和实现。

 

 

下面列出经常使用的场景及封装的方法:

1.消息类型转换器

2.配置拦截器

3.进行spring validation 验证

4.默认跳转视图配置

5.静态资源跳转

6.跨域设置

package com.lf.mp.test;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.lang.Nullable;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import javax.servlet.Filter;
import java.nio.charset.Charset;
import java.util.List;

@EnableWebMvc
@Configuration
public class SpringMvcConfig implements WebMvcConfigurer {
    // 自定义消息类型转换器
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(new StringHttpMessageConverter(Charset.defaultCharset()));
        converters.add(jsonHttpMessageConverter());
    }

    // spring中创建 FastJsonHttpMessageConverter bean
    @Bean
    public FastJsonHttpMessageConverter jsonHttpMessageConverter() {
        return new FastJsonHttpMessageConverter();
    }

    /**
     *  配置拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new TestInterceptor()).addPathPatterns("/**").excludePathPatterns("/emp/toLogin", "/emp/login", "/js/**", "/css/**", "/images/**");
    }

    @Bean
    public Filter characterEncodingFilter() {
        CharacterEncodingFilter filter = new CharacterEncodingFilter();
        filter.setEncoding("UTF-8");
        filter.setForceEncoding(true);
        return filter;
    }

    @Nullable
    @Override
    public Validator getValidator() {
        return new LocalValidatorFactoryBean();
    }

    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
        return new MethodValidationPostProcessor();
    }

    /**
     * 默认跳转到视图
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
    }

    /**
     * 视图处理器
     */
    @Bean
    public InternalResourceViewResolver configureInternalResourceViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

    /**
     * 静态资源跳转
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        // 一些系统的静态配置
        registry.addResourceHandler("/data/**").addResourceLocations("file:/home/pplive/data/");
    }

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