首页 > 解决方案 > Spring MVC:属性文件中的验证错误消息不显示

问题描述

我知道这是一个重复的问题,但是我遵循了该领域的所有建议,无法得出为什么它不起作用的结论:

这是我的控制器代码

@RequestMapping("/submitForm")
    String submitForm(
            @Valid
            @ModelAttribute("student")
            StudentRepository student,  BindingResult bindingResult)
    { ...

这是bean定义:

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

我的 Java 对象/Bean 参数验证约束:

public class StudentRepository {

    @Size(min = 1,max = 3)
    private String firstName;
    ....

而且,这是应该保存错误消息的属性文件:

#typeMismatch.studentRepository.age= Invalid Number
#org.hibernate.validator.constraints.NotEmpty.firstName = First Name Shouldn't Be Empty
Size.student.firstName = Too long text

JSP 视图文件:

First Name: <form:input type="text" path="firstName" /> <br/>
            <form:errors path="firstName" cssClass="error"/>

这个设置可能有什么问题?

编辑:

验证工作正常,与验证注释内联的验证消息也工作正常,即:@Size(min=1,message"error")

我可以让它工作的是我们填充属性文件的错误消息

编辑2:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc.xsd
            http://www.springframework.org/schema/util
            http://www.springframework.org/schema/util/spring-util.xsd">

<!--  Step 3: Add support for component scanning  -->
    <context:component-scan base-package="com.myCode.springdemo"/>
    <!--
     Step 4: Add support for conversion, formatting and validation support
    -->
    <mvc:annotation-driven/>
    <!--  Step 5: Define Spring MVC view resolver  -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!-- Loading propeties file to be injected in Beans and used in views-->
    <util:properties id="countryOptions" location="classpath:error-messges.properties" />

    <!-- Loading error messages from properties file-->
    <!-- Register the messages properties-->
    <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="error-messges"/>
    </bean>


</beans>

标签: javaspringspring-mvc

解决方案


推荐阅读