Spring 3 MVC:使用自定义验证器显示验证消息 [英] Spring 3 MVC: Show validation message with custom validator

查看:19
本文介绍了Spring 3 MVC:使用自定义验证器显示验证消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我的验证器类

 包验证器;导入模型.用户模型;导入 org.springframework.stereotype.Component;导入 org.springframework.validation.Errors;导入 org.springframework.validation.ValidationUtils;导入 org.springframework.validation.Validator;@零件公共类 UserValidator 实现了 Validator {@覆盖公共布尔支持(类 clazz){返回 UserModel.class.isAssignableFrom(clazz);}@覆盖公共无效验证(对象目标,错误错误){ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstname", "Enter firstname.");ValidationUtils.rejectIfEmptyOrWhitespace(errors, "surname", "Enter surname.");ValidationUtils.rejectIfEmptyOrWhitespace(errors, "login", "Enter login.");}}

控制器类

包控制器;导入 java.util.ArrayList;导入模型.用户模型;导入 org.springframework.stereotype.Controller;导入 org.springframework.validation.BindingResult;导入 org.springframework.web.bind.annotation.ModelAttribute;导入 org.springframework.web.bind.annotation.RequestMapping;导入 org.springframework.web.bind.annotation.RequestMethod;导入 org.springframework.web.servlet.ModelAndView;导入验证器.UserValidator;导入数据库.UserDB;@控制器公共类用户控制器{@RequestMapping(value="pouzivatel/new", method=RequestMethod.POST)public ModelAndView newUser(@ModelAttribute UserModel 用户,BindingResult 结果){UserValidator 验证器 = new UserValidator();验证器.验证(用户,结果);如果(结果.hasErrors()){return new ModelAndView("/user/new","command",user);}...}

用户模型

包模型;公共类用户模型{私人字符串名字="";私人字符串姓氏="";公共字符串 getFirstname() {返回名字;}公共字符串 getSurname() {回姓;}public void setFirstname(String firstname) {this.firstname = 名字;}公共无效setSurname(字符串姓氏){this.surname = 姓氏;}}

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

<字段集><表格><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></fieldset><div><button type="submit" id="btOk">Ok</button>

</form:form>

调度程序servlet.xml

<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></豆类>

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

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

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

你能举个例子吗?

感谢回复.

解决方案

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

  • 当您编写没有 modelAttribute(或 commandName)属性的 时,它使用默认模型属性名称 命令.
  • 当您在控制器中编写 @ModelAttribute UserModel user 时,它假定该属性的名称是一个去大写的类名,即 userModel.

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

您需要在视图 (<form:form modelAttribute = "userModel" ...>) 或控制器 (@ModelAttribute("command")).

I need help. I am beginner in jsp, MVC. I want to validate form input with custom validator in 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)

<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

<?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

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.

解决方案

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 user in your controller, it assumes that the name of this attribute is a decapitalized class name, i.e. 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.

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

这篇关于Spring 3 MVC:使用自定义验证器显示验证消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆