简体   繁体   中英

spring-mvc @Size annotation does not resolve error message correctly

I am trying to use Validator from Spring with ValidationMessages.properties to define error messages defined in javax annotations ( @NotNull , @Size etc). However, instead of resolved message the raw string (like "Size.firstName.length") is printed. Moreover, tomcat shows a warning which says

WARNING: ResourceBundle [/WEB-INF/messages/] not found for MessageSource: Can't find bundle for base name /WEB-INF/messages/, locale en_US

Additionally, I also checked similar questions in here but nothing worked. Lets say this is a simple Person POJO.

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

public class User {

    @NotNull
    @Size(min = 2, max = 10, message = "Size.firstName.length")
    private String firstName;

    @NotNull
    @Size(min = 2, max = 10)
    private String lastName;

    public User() {};

    public User(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

...
}

and related config the related jsp file is like below,

WebConfig.java

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"spittr.web", "spittr.data"})
public class WebConfig extends WebMvcConfigurerAdapter {

    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        resolver.setExposeContextBeansAsAttributes(true);
        return resolver;
    }

    @Bean
    public MessageSource messageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasename("/WEB-INF/messages/");
        return messageSource;
    }

    @Bean
    public LocalValidatorFactoryBean validatorFactory() {
        LocalValidatorFactoryBean factoryBean = new LocalValidatorFactoryBean();
        factoryBean.setValidationMessageSource(messageSource());
        return factoryBean;
    }

    @Override
    public Validator getValidator() {
        return validatorFactory();
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}

registerForm.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="sf" %>
<%@ page session="false" %>

<html>
    <head>
        <title>Spittr</title>
        <link href="<c:url value="/resources/css/user.css" />" rel="stylesheet">
    </head>
    <body>
        <h1>Register</h1>
        <sf:form method="POST" commandName="user">
            First Name: <sf:input path="firstName"/>
                        <sf:errors path="firstName" cssClass="error"/><br/>
            Last Name: <sf:input path="lastName"/>
                       <sf:errors path="lastName" cssClass="error"/><br/>
            <input type="submit" value="Register">
        </sf:form>
    </body>
</html>

ValidationMessages.properties

firstName.size=First Name must be between {min} and {max} charatecters long.

And ValidationMessages.properties is under

- webapp
  - WEB-INF
    - messages
      - ValidationMessages.properties

So, as I said if firstName is invalid, error message is not rendered and raw string of "Size.firstName.length" is shown.

Spring delegates the message lookup to the configured MessageSource it doesn't use the ValidationMessages.properties for that. (That is what default bean validation does!).

However the configuration of your MessageSource is wrong. The baseName should be a file name NOT a directory. Next you are using a ResourceBundleMessageSource which is only capable of loading files from the classpath . Reconfigure your MessageSource .

@Bean
public MessageSource messageSource() {
    ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
    messageSource.setBasename("messages");
    return messageSource;
}

Now rename your ValidationMessages.properties to messages.properties and put it in src\\main\\resources\\ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM