【问题标题】:Not able to print message from properties file using size annotation using spring-mvc无法使用 spring-mvc 使用大小注释从属性文件中打印消息
【发布时间】:2015-07-04 18:22:38
【问题描述】:

我对 Spring MVC 完全陌生。我有一个带有以下注释的Student

@Size(min=2, max=10 )
public String studentHobby;

还有一个StudentController 类:

@RequestMapping("admissionSuccess.html")
public ModelAndView admissionSuccess(@Valid @ModelAttribute("student") Student student,BindingResult result)
{

    if(result.hasErrors())
    {
        ModelAndView model=new ModelAndView("admissionForm");
        return model;
    }
    ModelAndView model=new ModelAndView("admissionSuccess");
    model.addObject("student",student);
    return model;
}

studentmessages.properties:

Size.student.studentHobby=please enter a value for studenthobby  between 2 and 10;

spring-servlet.xml 文件:

<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basename" value="/WEB-INF/studentmessages/"></property>
</bean>

我无法从属性文件中打印消息,我收到的是默认消息。请告诉我代码是否有问题。

【问题讨论】:

    标签: java spring spring-mvc


    【解决方案1】:

    您的目录结构如何?看起来您设置了您的 ReloadableResourceBundle 的基本名称以匹配您的属性文件名。相反,它必须与您放置消息文件的文件夹匹配。并将studentmessages.properties 重命名为ValidationMessages.properties(验证消息的默认资源包)。

    像这样:

    <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basename" value="/WEB-INF/messages/"></property>
    </bean>
    

    并将其添加到您的配置 xml:

    <bean id=”validator” class=”org.springframework.validation.beanvalidation.LocalValidatorFactoryBean” >
        <property name=”validationMessageSource” ref=”messageSource”/>
    </bean>
    

    目录结构:

    ...
       |_ WEB-INF
             |_ messages
                   |_ ValidationMessages.properties
    

    并且您应该在模型的属性中指定应该在验证时使用哪个消息(如 Igor Patsyan 所说)。像这样:

    @Size(min=2, max=10, message="Size.student.studentHobby")
    public String studentHobby;
    

    参考:http://www.silverbaytech.com/2013/04/16/custom-messages-in-spring-validation/

    【讨论】:

      【解决方案2】:

      需要给注解@Size添加属性message

      @Size(min=2, max=10, message = 'Size.student.studentHobby' )
      

      如果您不定义此属性,则会自动生成一条消息:

      "size must be between 2 and 10"
      

      你还需要:

      1. messageSource bean 中为您的属性文件定义正确的路径WEB-INF/i18n/messages

      2. 在配置文件中配置LocalValidatorFactoryBean

      3. 在控制器中注入声明的验证器并使用它。

      如图here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-07-09
        • 2017-11-25
        • 2011-08-12
        • 2018-07-20
        • 1970-01-01
        • 1970-01-01
        • 2014-05-04
        相关资源
        最近更新 更多