Search code examples
javaspring-bootasciibean-validationexceptionhandler

Spring boot 2.0.X properties exceptionhandler response ascii?


everybody,i am using boot 2.0.x,project encoding and charset are UTF-8, request and response as same,but when using bean validation 2, to convert error msg,it shows ascii? 1:defined a bean such as 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:using global exception handler:

    @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:define ValidationMessages.properties:

bv2.email.invalid = mail address is invalid,邮件地址无效!
bv2.email.required = mail address is required,邮件地址为必填项!

4:write controller to handle request:

@PostMapping("/bv2")
public Boolean jsr380(@Valid @RequestBody BeanValidation bv2) {
    return null == bv2 ? false : true;
}

5:start application and request via Postman with request parameter: http://localhost:12345/contextPath/bv2, request data:

{"email":"email address"}

response result:

{
            "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"
        }
  1. it response success,but it encode ascii automaticly,so my question is: "defaultMessage": "mail address is invalid,é\u0082®ä»¶å\u009c°å\u009d\u0080æ\u0097 æ\u0095\u0088!",

when i using simpled chinese,it appears such as ascii code, how to show or decode to normal such as:

mail address is invalid,邮件地址无效!
        mail address is required,邮件地址为必填项!

thank you all!


Solution

  • i resolved it as a global way:

    @Configuration
    

    public class WebConfig implements 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 under src/main/resources/i18n/bvMsg

    bv2.price.min = 最低价格是666!
    bv2.price.positive = 价格必须是正数!
    
    bv2.email.invalid = 邮件地址无效!
    bv2.email.required = 邮件地址为必填项!
    

    response,it works as follows:

    {
    "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"
    

    }