大家,我正在使用引导2.0.x,项目编码和字符集均为UTF-8,
    请求和响应相同,但是在使用bean验证2时,
    转换错误味精,它显示ASCII?
1:定义一个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:启动应用程序并通过邮递员使用请求参数进行请求:
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”:“邮件地址无效,é\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!

关于java - Spring Boot 2.0.X属性异常处理程序响应ascii?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52452840/

10-13 22:57