Spring 启动 2.0.X 属性异常处理程序响应 ascii?
Spring boot 2.0.X properties exceptionhandler response ascii?
各位,我用的是boot 2.0.x,项目编码和字符集都是UTF-8,
请求和响应相同,但使用 bean 验证 2 时,
转换错误消息,它显示 ascii?
1:defined 一个 bean,例如 BeanValidation.java:
@Data
public class BeanValidation implements Serializable{
private static final long serialVersionUID = 6265504102271769397L;
@Email(message = "{bv2.email.invalid}")
@NotEmpty(message = "{bv2.email.required}")
private String email;
}
2:使用全局异常处理程序:
@RestControllerAdvice
public class GenericExceptionHandler
extends ResponseEntityExceptionHandler
implements ErrorController{
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid1(
MethodArgumentNotValidException ex,
HttpHeaders headers,HttpStatus status,WebRequest request) {
BindingResult br = ex.getBindingResult();
List<String> errorList = new ArrayList<String>();
br.getFieldErrors().forEach(fe -> {
errorList.add(fe.getField() + ":" + fe.getDefaultMessage());
});
br.getGlobalErrors().forEach(ge -> {
errorList.add(ge.getObjectName() + ":" + ge.getDefaultMessage());
});
ApiError apiError = new ApiError(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), errorList);
return handleExceptionInternal(ex, apiError, headers, apiError.getStatus(), request);
}
}
3:定义ValidationMessages.properties:
bv2.email.invalid = mail address is invalid,邮件地址无效!
bv2.email.required = mail address is required,邮件地址为必填项!
4:写控制器来处理请求:
@PostMapping("/bv2")
public Boolean jsr380(@Valid @RequestBody BeanValidation bv2) {
return null == bv2 ? false : true;
}
5:启动应用,通过Postman请求参数:
http://localhost:12345/contextPath/bv2,
请求数据:
{"email":"email address"}
响应结果:
{
"timestamp": "2018-09-22T01:50:09.729+0000",
"status": "400",
"error": "Bad Request",
"errors": [
{
"defaultMessage": "mail address is invalid,é\u0082®ä»¶å\u009c°å\u009d\u0080æ\u0097 æ\u0095\u0088!",
"objectName": "beanValidation",
"field": "email",
"rejectedValue": "email address",
"bindingFailure": false,
"code": "Email"
}
],
"message": "Bad Request",
"path": "/contextPath/bv2"
}
- 它响应成功,但它自动编码为ascii,所以我的问题是:
"defaultMessage": "mail address is invalid,é\u0082®ä»¶å\u009c°å\u009d\u0080æ\u0097 æ\u0095\u0088!",
当我使用简体中文时,出现了ascii码,
如何显示或解码为正常如:
mail address is invalid,邮件地址无效!
mail address is required,邮件地址为必填项!
谢谢大家!
根据我的经验,您可以在文件 'xxx.properties'
中执行此操作
bv2.email.invalid = mail address is invalid,é\u0082®ä»¶å\u009c°å\u009d\u0080æ\u0097 æ\u0095\u0088!
在属性文件中定义默认编码类型。
尝试使用
spring.messages.encoding=UTF-8
在 application.properties 文件中。
我以全局方式解决了它:
@Configuration
public class WebConfig 实现WebMvcConfigurer{
@Override
public Validator getValidator() {
return validator();
}
@Bean
public LocalValidatorFactoryBean validator() {
final LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
validator.setValidationMessageSource(messageSource());
return validator;
}
/**
* @title:messageSource:base name sequence:i18n and bean validation use this
* [baseName]_[language]_[script]_[region]_[variant]
* [baseName]_[language]_[script]_[region]
* [baseName]_[language]_[script]
* [baseName]_[language]_[region]_[variant]
* [baseName]_[language]_[region]
* [baseName]_[language]
* @return MessageSource
* @create 2018-09-25 09:32:24
* @author:elf
* @since:1.0.0
*/
@Bean
public ReloadableResourceBundleMessageSource messageSource() {
ReloadableResourceBundleMessageSource source = new ReloadableResourceBundleMessageSource();
String[] baseNameArray = {
"classpath:i18n/msg",
"classpath:i18n/bvMsg",
"classpath:i18n/commonMsg",
};
source.setBasenames(baseNameArray);
source.setDefaultEncoding(StandardCharsets.UTF_8.name());
return source;
}
}
bvMsg.properties 在 src/main/resources/i18n/bvMsg
下
bv2.price.min = 最低价格是666!
bv2.price.positive = 价格必须是正数!
bv2.email.invalid = 邮件地址无效!
bv2.email.required = 邮件地址为必填项!
响应,它的工作原理如下:
{
"timestamp": "2018-09-25T07:05:03.420+0000",
"status": "400",
"error": "Bad Request",
"errors": [
{
"codes": [
"Positive.beanValidation.price",
"Positive.price",
"Positive.java.lang.Integer",
"Positive"
],
"arguments": [
{
"codes": [
"beanValidation.price",
"price"
],
"arguments": null,
"defaultMessage": "price",
"code": "price"
}
],
"defaultMessage": "价格必须是正数!",
"objectName": "beanValidation",
"field": "price",
"rejectedValue": "-333",
"bindingFailure": false,
"code": "Positive"
},
{
"codes": [
"Email.beanValidation.email",
"Email.email",
"Email.java.lang.String",
"Email"
],
"arguments": [
{
"codes": [
"beanValidation.email",
"email"
],
"arguments": null,
"defaultMessage": "email",
"code": "email"
},
[],
{
"arguments": null,
"defaultMessage": ".*",
"codes": [
".*"
]
}
],
"defaultMessage": "邮件地址无效!",
"objectName": "beanValidation",
"field": "email",
"rejectedValue": "fdsaomc.com",
"bindingFailure": false,
"code": "Email"
},
{
"codes": [
"Min.beanValidation.price",
"Min.price",
"Min.java.lang.Integer",
"Min"
],
"arguments": [
{
"codes": [
"beanValidation.price",
"price"
],
"arguments": null,
"defaultMessage": "price",
"code": "price"
},
"666"
],
"defaultMessage": "最低价格是666!",
"objectName": "beanValidation",
"field": "price",
"rejectedValue": "-333",
"bindingFailure": false,
"code": "Min"
}
],
"message": "Bad Request",
"path": "/contextPath/bv2"
}
各位,我用的是boot 2.0.x,项目编码和字符集都是UTF-8, 请求和响应相同,但使用 bean 验证 2 时, 转换错误消息,它显示 ascii? 1:defined 一个 bean,例如 BeanValidation.java:
@Data
public class BeanValidation implements Serializable{
private static final long serialVersionUID = 6265504102271769397L;
@Email(message = "{bv2.email.invalid}")
@NotEmpty(message = "{bv2.email.required}")
private String email;
}
2:使用全局异常处理程序:
@RestControllerAdvice
public class GenericExceptionHandler
extends ResponseEntityExceptionHandler
implements ErrorController{
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid1(
MethodArgumentNotValidException ex,
HttpHeaders headers,HttpStatus status,WebRequest request) {
BindingResult br = ex.getBindingResult();
List<String> errorList = new ArrayList<String>();
br.getFieldErrors().forEach(fe -> {
errorList.add(fe.getField() + ":" + fe.getDefaultMessage());
});
br.getGlobalErrors().forEach(ge -> {
errorList.add(ge.getObjectName() + ":" + ge.getDefaultMessage());
});
ApiError apiError = new ApiError(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), errorList);
return handleExceptionInternal(ex, apiError, headers, apiError.getStatus(), request);
}
}
3:定义ValidationMessages.properties:
bv2.email.invalid = mail address is invalid,邮件地址无效!
bv2.email.required = mail address is required,邮件地址为必填项!
4:写控制器来处理请求:
@PostMapping("/bv2")
public Boolean jsr380(@Valid @RequestBody BeanValidation bv2) {
return null == bv2 ? false : true;
}
5:启动应用,通过Postman请求参数: http://localhost:12345/contextPath/bv2, 请求数据:
{"email":"email address"}
响应结果:
{
"timestamp": "2018-09-22T01:50:09.729+0000",
"status": "400",
"error": "Bad Request",
"errors": [
{
"defaultMessage": "mail address is invalid,é\u0082®ä»¶å\u009c°å\u009d\u0080æ\u0097 æ\u0095\u0088!",
"objectName": "beanValidation",
"field": "email",
"rejectedValue": "email address",
"bindingFailure": false,
"code": "Email"
}
],
"message": "Bad Request",
"path": "/contextPath/bv2"
}
- 它响应成功,但它自动编码为ascii,所以我的问题是: "defaultMessage": "mail address is invalid,é\u0082®ä»¶å\u009c°å\u009d\u0080æ\u0097 æ\u0095\u0088!",
当我使用简体中文时,出现了ascii码, 如何显示或解码为正常如:
mail address is invalid,邮件地址无效!
mail address is required,邮件地址为必填项!
谢谢大家!
根据我的经验,您可以在文件 'xxx.properties'
中执行此操作bv2.email.invalid = mail address is invalid,é\u0082®ä»¶å\u009c°å\u009d\u0080æ\u0097 æ\u0095\u0088!
在属性文件中定义默认编码类型。
尝试使用
spring.messages.encoding=UTF-8
在 application.properties 文件中。
我以全局方式解决了它:
@Configuration
public class WebConfig 实现WebMvcConfigurer{
@Override
public Validator getValidator() {
return validator();
}
@Bean
public LocalValidatorFactoryBean validator() {
final LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
validator.setValidationMessageSource(messageSource());
return validator;
}
/**
* @title:messageSource:base name sequence:i18n and bean validation use this
* [baseName]_[language]_[script]_[region]_[variant]
* [baseName]_[language]_[script]_[region]
* [baseName]_[language]_[script]
* [baseName]_[language]_[region]_[variant]
* [baseName]_[language]_[region]
* [baseName]_[language]
* @return MessageSource
* @create 2018-09-25 09:32:24
* @author:elf
* @since:1.0.0
*/
@Bean
public ReloadableResourceBundleMessageSource messageSource() {
ReloadableResourceBundleMessageSource source = new ReloadableResourceBundleMessageSource();
String[] baseNameArray = {
"classpath:i18n/msg",
"classpath:i18n/bvMsg",
"classpath:i18n/commonMsg",
};
source.setBasenames(baseNameArray);
source.setDefaultEncoding(StandardCharsets.UTF_8.name());
return source;
}
}
bvMsg.properties 在 src/main/resources/i18n/bvMsg
下bv2.price.min = 最低价格是666!
bv2.price.positive = 价格必须是正数!
bv2.email.invalid = 邮件地址无效!
bv2.email.required = 邮件地址为必填项!
响应,它的工作原理如下:
{
"timestamp": "2018-09-25T07:05:03.420+0000",
"status": "400",
"error": "Bad Request",
"errors": [
{
"codes": [
"Positive.beanValidation.price",
"Positive.price",
"Positive.java.lang.Integer",
"Positive"
],
"arguments": [
{
"codes": [
"beanValidation.price",
"price"
],
"arguments": null,
"defaultMessage": "price",
"code": "price"
}
],
"defaultMessage": "价格必须是正数!",
"objectName": "beanValidation",
"field": "price",
"rejectedValue": "-333",
"bindingFailure": false,
"code": "Positive"
},
{
"codes": [
"Email.beanValidation.email",
"Email.email",
"Email.java.lang.String",
"Email"
],
"arguments": [
{
"codes": [
"beanValidation.email",
"email"
],
"arguments": null,
"defaultMessage": "email",
"code": "email"
},
[],
{
"arguments": null,
"defaultMessage": ".*",
"codes": [
".*"
]
}
],
"defaultMessage": "邮件地址无效!",
"objectName": "beanValidation",
"field": "email",
"rejectedValue": "fdsaomc.com",
"bindingFailure": false,
"code": "Email"
},
{
"codes": [
"Min.beanValidation.price",
"Min.price",
"Min.java.lang.Integer",
"Min"
],
"arguments": [
{
"codes": [
"beanValidation.price",
"price"
],
"arguments": null,
"defaultMessage": "price",
"code": "price"
},
"666"
],
"defaultMessage": "最低价格是666!",
"objectName": "beanValidation",
"field": "price",
"rejectedValue": "-333",
"bindingFailure": false,
"code": "Min"
}
],
"message": "Bad Request",
"path": "/contextPath/bv2"
}