Spring MVC 自定义验证器示例

Spring MVC 自定义验证器示例

原文: https://howtodoinjava.com/spring-mvc/spring-mvc-custom-validator-example/

spring mvc 表单提交教程中,我们学习了如何显示显示表单和提交表单数据,包括使用BindingResult.rejectValue()验证输入。 在此示例中,我们将学习为EmployeeVO模型对象构建更强大的验证器。 该验证器是 Validator 接口的自定义实现。 在此示例中,我将修改上一个教程中构建的表单提交示例所使用的代码。

阅读更多: Spring MVC 显示,验证和提交表单示例

下载源码

自定义验证器实现

Spring MVC 通过实现Validator接口的验证器对象来支持验证。 您可以编写以下验证器来检查是否填写了必需的表单字段。

package com.howtodoinjava.demo.validator;

import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.howtodoinjava.demo.model.EmployeeVO;

@Component
public class EmployeeValidator implements Validator 
{

	public boolean supports(Class clazz) {
		return EmployeeVO.class.isAssignableFrom(clazz);
	}

	public void validate(Object target, Errors errors) 
	{
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "error.firstName", "First name is required.");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "error.lastName", "Last name is required.");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "error.email", "Email is required.");
	}

}

在此验证器中,您可以使用ValidationUtils类中的rejectIfEmptyOrWhitespace()rejectIfEmpty()之类的实用方法来验证所需的表单字段。 如果这些表单字段中的任何一个为空,这些方法将创建一个字段错误并将其绑定到该字段。 这些方法的第二个参数是属性名称,而第三个和第四个是错误代码和默认错误消息。

很多时候,验证错误并非特定于字段。 例如,结束日期应大于开始日期。 在这种情况下,可以使用reject()方法创建要绑定到EmployeeVO对象而不是字段的对象错误。

例如errors.reject("invalid.dateDiff", "结束日期应大于开始日期。");

要将此自定义验证器激活为 spring 托管 bean,您需要执行以下操作之一:

1)在EmployeeValidator类中添加@Component注解,并在包含此类声明的包上激活注解扫描。

<context:component-scan base-package="com.howtodoinjava.demo" />

2)或者,您可以直接在上下文文件中注册验证器类 bean。

<bean id="employeeValidator" class="com.howtodoinjava.demo.validator.EmployeeValidator" />

控制器变更

要应用此验证器,您需要对控制器执行以下修改。

1)包括控制器类的验证器引用,并对其进行自动标记,以确保在需要时可用。

@Autowired
EmployeeValidator validator;

2)下一个更改是在控制器的 post 方法中,该方法在用户提交表单时调用。

@RequestMapping(method = RequestMethod.POST)
public String submitForm(@ModelAttribute("employee") EmployeeVO employeeVO,
						BindingResult result, SessionStatus status) 
{

	//Validation code
	validator.validate(employeeVO, result);

	//Check validation errors
	if (result.hasErrors()) {
		return "addEmployee";
	}

	//Store the employee information in database
	//manager.createNewRecord(employeeVO);

	//Mark Session Complete
	status.setComplete();
	return "redirect:addNew/success";
}

验证方法返回后,结果参数(即BindingResult)将包含验证过程的结果。 您可以使用result.hasErrors()方法调用检查输入是否有错误。 如果检测到任何错误,您可以再次渲染表单视图,以使用户更正其输入。

如果未发现错误,则result.hasErrors()将返回false,然后您可以简单地处理输入并将用户重定向到下一个视图。

本示例中使用的完整源代码敌人控制器如下:

package com.howtodoinjava.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import com.howtodoinjava.demo.model.EmployeeVO;
import com.howtodoinjava.demo.service.EmployeeManager;
import com.howtodoinjava.demo.validator.EmployeeValidator;

@Controller
@RequestMapping("/employee-module/addNew")
@SessionAttributes("employee")
public class EmployeeController 
{
	@Autowired
	EmployeeManager manager;

	@Autowired
	EmployeeValidator validator;

	@RequestMapping(method = RequestMethod.GET)
    public String setupForm(Model model) 
	{
		 EmployeeVO employeeVO = new EmployeeVO();
		 model.addAttribute("employee", employeeVO);
		 return "addEmployee";
    }

	@RequestMapping(method = RequestMethod.POST)
    public String submitForm(@ModelAttribute("employee") EmployeeVO employeeVO,
            				BindingResult result, SessionStatus status) 
	{

		validator.validate(employeeVO, result);

		if (result.hasErrors()) {
			return "addEmployee";
		}
		//Store the employee information in database
		//manager.createNewRecord(employeeVO);

		//Mark Session Complete
		status.setComplete();
		return "redirect:addNew/success";
    }

	@RequestMapping(value = "/success", method = RequestMethod.GET)
    public String success(Model model) 
	{
		 return "addSuccess";
    }
}

下载源码

将您的问题放到我的评论部分。

祝您学习愉快!