记 SpringBoot1.* 转 Springoot2.0 遇到的问题
阅读原文时间:2023年07月10日阅读:2

1.拦截器问题

到2.0之后在配置文件中写 static-path-pattern: /static/** 已经不起作用(2.0需要在方法中配置)

SpringBoot1.*写法

@Configuration

public class WebMvcConfig extends WebMvcConfigurerAdapter {

private final UserMethodArgumentResolver userMethodArgumentResolver;  
@Autowired  
public JwtInterceptor(UserMethodArgumentResolver userMethodArgumentResolver) {  
    this.userMethodArgumentResolver = userMethodArgumentResolver;

}

@Override  
public void addInterceptors(InterceptorRegistry registry) {  
    registry.addInterceptor(getWebmvcConfig())  
            .addPathPatterns("/\*\*")//拦截  
            .excludePathPatterns("/",//排除拦截  

          "/login/**");

    super.addInterceptors(registry);  
}

@Bean  
public WebmvcConfig getWebmvcConfig() {  
    return new WebmvcConfig();  
}

@Override  
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {  
    argumentResolvers.add(userMethodArgumentResolver);  
}  

}

SpringBoot2.0写法

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
private static final Logger LOGGER = LoggerFactory.getLogger(WebMvcConfig.class);

@Override  
public void addResourceHandlers(ResourceHandlerRegistry registry) {//设置资源路径  
    registry.addResourceHandler("/static/\*\*").addResourceLocations("classpath:/static/");  
    super.addResourceHandlers(registry);  
}  
@Override  
public void addInterceptors(InterceptorRegistry registry) {  
    registry.addInterceptor(new JwtInterceptor())  
            .addPathPatterns("/\*\*")//拦截  
            .excludePathPatterns("/",//排除拦截"/login/\*\*","/static/\*\*");  
}

}

2.编码问题

页面访问不会出现乱码现象,但是Ajax请求返回的中文会出现乱码,经过排查是由于 ResponseBody 引用 StringHttpMessageConverter 这个类,而此类默认编码为ISO_8859_1,我们需要更改为UTF-8。

此代码段放到继承 WebMvcConfigurationSupportl 类的 WebMvcConfig 类下

/\*\*  
 \* 设置默认编码为UTF-8  
 \*/  
@Bean  
public HttpMessageConverter<String> responseBodyConverter() {  
    final StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));  
    converter.setWriteAcceptCharset(false);  
    return converter;  
}  
@Override  
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {  
    converters.add(responseBodyConverter());  
    addDefaultHttpMessageConverters(converters);  
}  
@Override  
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {  
    configurer.favorPathExtension(false);  
}

  默认的 StringHttpMessageConverter 会加上 Accept-Charset 响应头并带上所有的字符集,需要设置一下

  converter.setWriteAcceptCharset(false);