Spring boot 2.0.X properties exceptionhandler response ascii?

spring boot wiki
spring boot download
spring boot tutorial
spring boot initializr
spring-boot maven
spring boot mvc
spring boot latest version
spring boot documentation

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!


As my experience, you can do this in file 'xxx.properties'

bv2.email.invalid = mail address is invalid,é\u0082®ä»¶å\u009c°å\u009d\u0080æ\u0097 æ\u0095\u0088!

Spring boot 404 error custom error response ReST, For those Spring Boot 2 users who don't wanna use @EnableWebMvc. application.properties server.error.whitelabel.enabled=false  Spring boot exception handling – @ExceptionHandler example By Lokesh Gupta | Filed Under: Spring Boot 2 In this spring boot exception handler tutorial, we will learn to validate request body sent to PUT/POST REST APIs.


Define default encoding type in properties file.

Try using

spring.messages.encoding=UTF-8

in application.properties file.

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,  Spring Boot – Inject Application Arguments in @Bean and @Compoment Spring Boot 2 – OAuth2 Auth and Resource Server Spring boot async controller with SseEmitter


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"

}

Spring Boot Reference Documentation, Loading YAML; Exposing YAML as Properties in the Spring Environment; Multi-​profile Gradle 5.6.x is also supported but this support is deprecated and will be sdk install springboot $ spring --version Spring Boot v2.3.0. Also, Spring MVC can add HTTP caching headers to responses when serving static resources​. Spring Boot uses some relaxed rules for binding Environment properties to @ConfigurationProperties beans, so there doesn’t need to be an exact match between the Environment property name and the bean property name.


Spring Boot Reference Guide, Exposing YAML as properties in the Spring Environment; 24.6.3. Multi-profile YAML sdk install springboot $ spring --version Spring Boot v2.0.0.M2. If you are​  Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can "just run". We take an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss. Most Spring Boot applications need very little Spring configuration. Embed Tomcat, Jetty or Undertow directly


Web on Servlet Stack - Project Metadata API Guide, Alternatively, for annotated controllers, the response can be rendered (within the by using an @ExceptionHandler controller method) and handled as any others​. in your Spring configuration and setting their order properties as needed. requests with a content type of application/x-www-form-urlencoded , read the form  How to install and get started with Java, Eclipse, Maven, JUnit, Mockito & Spring in 5 easy steps - in28minutes/getting-started-in-5-steps


Spring Boot Features, Exposing YAML as Properties in the Spring Environment; 2.7.3. SAML 2.0. 10.4​.1. Relying Party. 10.5. Actuator Security. 10.5.1. Cross Site Request Forgery Images are converted into an ASCII art representation and printed above any text banner. For example, you could use the following line in a UN*X shell:. Spring Boot interceptor example. Filter example in Spring Boot. Content negotiation example using Spring Boot. Deploy Spring boot war in JBoss EAP server. Jboss 7 EPA datasource configuration using oracle and spring boot. Deploy Spring Boot application on external Tomcat. Deploy multiple war files in JBoss to different port. Spring boot