Spring 3 MVC:使用自定义验证器显示验证消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4031266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 04:10:25  来源:igfitidea点击:

Spring 3 MVC: Show validation message with custom validator

model-view-controllerspringvalidationjsp

提问by Jerry

I need help. I am beginner in jsp, MVC. I want to validate form input with custom validator in Spring 3 MVC.

我需要帮助。我是jsp,MVC的初学者。我想在 Spring 3 MVC 中使用自定义验证器验证表单输入。

My validator class

我的验证器类

   package validators;

import models.UserModel;

import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
@Component
public class UserValidator implements Validator {

   @Override
   public boolean supports(Class clazz) {
      return UserModel.class.isAssignableFrom(clazz);
   }

   @Override
   public void validate(Object target, Errors errors) {
      ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstname", "Enter firstname.");
      ValidationUtils.rejectIfEmptyOrWhitespace(errors, "surname", "Enter surname.");
      ValidationUtils.rejectIfEmptyOrWhitespace(errors, "login", "Enter login.");

   }

}

Controller class

控制器类

package controllers;

import java.util.ArrayList;
import models.UserModel;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import validators.UserValidator;
import database.UserDB;


@Controller
public class UserController {

@RequestMapping(value="pouzivatel/new", method=RequestMethod.POST)
   public ModelAndView newUser(@ModelAttribute UserModel user, BindingResult result){
      UserValidator validator = new UserValidator();
      validator.validate(user, result);
      if(result.hasErrors()){
         return new ModelAndView("/user/new","command",user);

      }
      ...
}

Model for User

用户模型

package models;

public class UserModel  {
   private String firstname="";
   private String surname="";

   public String getFirstname() {
      return firstname;
   }
   public String getSurname() {
      return surname;
   }

   public void setFirstname(String firstname) {
      this.firstname = firstname;
   }
   public void setSurname(String surname) {
      this.surname = surname;
   }

}

JSP veiw new.jsp which is in directory /web-inf/user (it just only form)

JSP 查看 new.jsp,它在目录 /web-inf/user 中(它只是表单)

<form:form method="post" action="new.html">
            <fieldset>
               <table>
                  <tr>
                     <td>
                        <form:label path="firstname">FirstName</form:label>
                     </td>
                     <td>
                        <form:input path="firstname" />
                        <form:errors path="firstname" />
                     </td>
                  </tr>
                  <tr>
                     <td>
                        <form:label path="surname">Surname</form:label>
                     </td>
                     <td>
                        <form:input path="surname" />
                        <form:errors path="surname" />
                     </td>
                  </tr>
               </table>
            </fieldset>
            <div>
               <button type="submit" id="btOk">Ok</button>
            </div>
</form:form>

dispatcher servlet.xml

调度程序servlet.xml

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

   <context:component-scan base-package="controllers" />
    <context:component-scan base-package="validators" />

   <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
      <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
      <property name="prefix" value="/WEB-INF/jsp/" />
      <property name="suffix" value=".jsp" />
   </bean>

</beans>

Problem is a display validation message in view. Validation is successful and in variable resut (BindingResult) are errors. Controller return follow part of code

问题是在视图中显示验证消息。验证成功并且在变量结果 (BindingResult) 中出现错误。控制器返回遵循部分代码

if(result.hasErrors()){
         return new ModelAndView("/user/new","command",user);

Another way is use Annotation validation (I preffer custom validator), but why i can not see validation messages on view, when input fields are empty.

另一种方法是使用注释验证(我喜欢自定义验证器),但是为什么当输入字段为空时我看不到验证消息。

Can you give me example how to do it right?

你能举个例子吗?

Thanks for reply.

谢谢您的回复。

回答by axtavt

This happens because of mismatch between default model attribute names in view and controller:

发生这种情况是因为视图和控制器中的默认模型属性名称不匹配:

  • When you write <form:form>without modelAttribute(or commandName) attribute, it uses default model attribute name command.
  • When you write @ModelAttribute UserModel userin your controller, it assumes that the name of this attribute is a decapitalized class name, i.e. userModel.
  • 当您在<form:form>没有modelAttribute(或commandName)属性的情况下编写时,它使用默认模型属性名称command
  • 当你@ModelAttribute UserModel user在你的控制器中编写时,它假设这个属性的名称是一个没有大写的类名,即userModel.

That is, error messages produced by validator are bound to model attribute named userModel, while your view tries to show errors for model attribute command.

也就是说,验证器生成的错误消息绑定到名为 的模型属性userModel,而您的视图尝试显示模型属性的错误command

You need to set a model attribute name explicitly, either in the view (<form:form modelAttribute = "userModel" ...>) or in the controller (@ModelAttribute("command")).

您需要在视图 ( <form:form modelAttribute = "userModel" ...>) 或控制器 ( @ModelAttribute("command")) 中显式设置模型属性名称。