springboot使用swagger2中文乱码,自定义异常的中文也乱码。
部分代码:
@Configuration
@EnableSwagger2
//@Component
public class SwaggerConfig implements WebMvcConfigurer
{
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations(
"classpath:/static/");
registry.addResourceHandler("swagger-ui.html").addResourceLocations(
"classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations(
"classpath:/META-INF/resources/webjars/");
WebMvcConfigurer.super.addResourceHandlers(registry);
}
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
ObjectMapper objectMapper = converter.getObjectMapper();
// 生成JSON时,将所有Long转换成String
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
objectMapper.registerModule(simpleModule);
// 时间格式化
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
// 设置格式化内容
converter.setObjectMapper(objectMapper);
converters.add(0, converter);
}
@Bean
public Docket webApiConfig(){
return new Docket(DocumentationType.SWAGGER_2)
.groupName("webApi")
.apiInfo(webApiInfo())
.select()
.paths(Predicates.not(PathSelectors.regex("/admin/.*")))
.paths(Predicates.not(PathSelectors.regex("/error.*")))
.build();
}
private ApiInfo webApiInfo(){
return new ApiInfoBuilder()
.title("仓库管理系统")
.description("本文档描述了仓库管理系统接口定义")
.version("1.0")
.contact(new Contact("Helen", "http://atguigu.com",
"55317332@qq.com"))
.build();
}
}
自定义异常
@Data
@AllArgsConstructor
@NoArgsConstructor
public class WNNException extends RuntimeException{
private Integer code;//异常状态码
private String msg;//异常信息
private boolean status;
}
配置类中配置异常类
//配置
@ExceptionHandler(WNNException.class)
public R error(WNNException e) {
e.printStackTrace();
return R.ok().message(new String(e.getMsg())).code(e.getCode()).success(e.isStatus());
}