【问题标题】:Adding custom error messages for validation in Spring-MVC在 Spring-MVC 中添加自定义错误消息以进行验证
【发布时间】:2014-11-19 12:37:59
【问题描述】:

我正在使用 Spring-MVC,我想在后端进行验证测试。目前我能够执行测试,正确重定向到链接。但如果出现问题,我只能添加自定义错误消息,例如:“名字为空”。我尝试在 WEB-INF 中使用 ValidationMessages_en_EN.properties 文件,但这也没有帮助。我正在发布我的代码,请告诉我哪里出错了:

控制器:

@Controller
public class PersonController {
 @RequestMapping(value = "/", method = RequestMethod.GET)
    public String listPersons(Model model) {
        Person person = personService.getCurrentlyAuthenticatedUser();
        if(!(person==null)){
            return "redirect:/canvas/list";
        } else {
            model.addAttribute("person", new Person());
         //   model.addAttribute("listPersons", this.personService.listPersons());
            model.addAttribute("notices",new Notes());
            model.addAttribute("canvases",new Canvas());
            return "person";
        }
    }

    @RequestMapping(value= "/person/add", method = RequestMethod.POST)
    public String addPerson(@Valid Person person,BindingResult bindingResult,@ModelAttribute("person") Person p,Model model){
        if(bindingResult.hasErrors()){
            return "redirect:/";
        }
            this.personService.addPerson(p);
            return "redirect:/";
    }

实体:

@Entity
@Table(name="person")
public class Person implements UserDetails{

    private static final GrantedAuthority USER_AUTH = new SimpleGrantedAuthority("ROLE_USER");

    @Id
    @Column(name="id")
    @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "person_seq_gen")
    @SequenceGenerator(name = "person_seq_gen",sequenceName = "person_seq")
    private int id;

    @Valid
    @NotEmpty @Email(message = "username.empty")
    @Column(name = "username")
    private String username;


    @NotEmpty
    @Column(name = "password")
    private String password;


    @Valid
    @Size(min = 2,max = 30,message = "firstName.empty")
    @Column(name = "firstname")
    private String firstName;

    @Valid
    @Size(min = 2,max = 50)
    @Column(name = "secretquestion")
    private String secretquestion;

    @Valid
    @Size(min = 2,max = 500,message = "secretanswer.empty")
    @Column(name = "secretanswer")
    private String secretanswer;

Servlet-Context.xml

<beans:bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <beans:property name="basename" value="ValidatorMessages_en_EN.properties"/>
           </beans:bean>

JSP/HTML:

      <c:url var="addAction" value="/person/add" ></c:url>
<form:form action="${addAction}" commandName="person" method="post">
<table>
    <c:if test="${!empty person.username}">
    <tr>
        <td>
            <form:label path="id">
                <spring:message text="ID"/>
            </form:label>
        </td>
        <td>
            <form:input path="id" readonly="true" size="8"  disabled="true" />
            <form:hidden path="id" />
        </td> 
    </tr>
    </c:if>

    <tr>
        <td>
            <form:label path="firstName">
                <spring:message text="FirstName"/>
            </form:label>
        </td>
        <td>
            <form:input path="firstName" />
        </td>
        <td><form:errors path="firstName"/>
    </tr>
    <tr>
        <td>
            <form:label path="username">
                <spring:message text="Email"/>
            </form:label>
        </td>
        <td>
            <form:input path="username" />
        </td>
        <td><form:errors path="username"/>
    </tr>
    <tr>
        <td>
            <form:label path="password">
                <spring:message text="Password"/>
            </form:label>
        </td>
        <td>
            <form:input path="password" />
        </td>
        <td><form:errors path="Password"/>
    </tr>

    <tr>
    <td>
        <form:label path="secretquestion">
            <spring:message text="secretquestion"/>
        </form:label>
    </td>
    <td>
        <form:input path="secretquestion" />
    </td>
        <td><form:errors path="secretquestion"/>
    </tr>


    <tr>
        <td>
            <form:label path="secretanswer">
                <spring:message text="secretanswer"/>
            </form:label>
        </td>
        <td>
            <form:input path="secretanswer" />
        </td>
        <td><form:errors path="secretanswer"/>
    </tr>

POM.xml:

 <!-- Validation -->
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.0.0.GA</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>4.3.1.Final</version>
        </dependency>

Messages.properties:

firstName=firstName
Email=Email
Password=password
secretquestion=secretquestion
secretanswer=secretanswer
NotEmpty.person.firstName=firstName is required!
NotEmpty.person.username=Email is required!
NotEmpty.person.password=Password is required!
NotEmpty.person.secretquestion=SecretQuestion is required!
NotEmpty.person.secretanswer=SecretAnswer is required!

Messages_en_US.properties

firstName=firstName
Email=Email
Password=password
secretquestion=secretquestion
secretanswer=secretanswer
NotEmpty.person.firstName=firstName is required!
NotEmpty.person.username=Email is required!
NotEmpty.person.password=Password is required!
NotEmpty.person.secretquestion=SecretQuestion is required!
NotEmpty.person.secretanswer=SecretAnswer is required!

【问题讨论】:

    标签: validation spring-mvc hibernate-validator


    【解决方案1】:

    &lt;spring:message text="FirstName"/&gt; 应该像 &lt;spring:message code="FirstName"/&gt; 尝试在您的 &lt;spring:message /&gt; 标记中替换 text to code

    并将 basename 值更改为 ValidatorMessagesen_US Spring 将为您附加

     <beans:bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
             <beans:property name="basename" value="ValidatorMessages"/>
     </beans:bean>
    

    将您的文件保存为ValidatorMessages_en_US.properties 在您的resource 文件夹中

    【讨论】:

    • 嗨 Pravin,您能否检查一下我在主帖中更新的错误日志以解决问题。
    • 这样做了,我现在可以在 IDE 中看到它可以找到文件。但我仍然收到这些错误。目前,在我的资源文件夹中有 2 个文件,messages.properties,messages_en_US.properties。 Servlet 属性值 =“消息”。尽管如此,还是没有运气。
    • 任何想法的人...我可以看到像 ResourceBundle 并比较文件中的不同语言。但它仍然给我同样的错误
    • 在您的资源文件夹中,ValidatorMessages_en_US.properties 必须与您输入 &lt;beans:property name="basename" value="ValidatorMessages"/&gt; 时一样存在
    • 嗨 Pravin,最后我更改了文件的位置并使其正常工作,但它仍然没有显示错误消息。就像当用户输入错误的用户名时,他应该看到用户名无效或其他什么。
    【解决方案2】:
    @ExceptionHandler(Exception.class)
    @ResponseBody 
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public Response handleException(Exception e) {          
        Response response = new Response();
        if(e instanceof MethodArgumentNotValidException ){
            MethodArgumentNotValidException methodException = (MethodArgumentNotValidException)e;
            BindingResult bindingResult =methodException.getBindingResult();
            if(bindingResult!=null && bindingResult.hasErrors()){
                List<FieldError> fieldErrorList= bindingResult.getFieldErrors();
                for(FieldError fieldError: fieldErrorList ){                    
                    response.adderror(fieldError.getDefaultMessage());
                }
            }
        }       
        return response;
    }
    

    【讨论】:

    • 你应该解释你的答案,而不仅仅是转储代码。
    • Response 来自哪个包?
    • 这是一个很好的答案,但对于一些易于理解的解释(例如,将这种方法放在哪里),请参见例如baeldung.com/…
    • @Benny:响应似乎是这里的自定义类。您想输入类似 ResponseEntity&lt;YourResponseBody&gt; 的内容。显式生成响应实体,您也可以省略@ResponseBody@ResponseStatus
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-30
    • 2012-05-07
    • 2019-04-21
    • 1970-01-01
    • 2014-07-10
    • 1970-01-01
    • 2016-03-27
    相关资源
    最近更新 更多