When using InitBinder for verification, some of the data submitted in this Controller needs to be of business nature, that is, it will only be used in relatively complex verification situations. Most simple form verification can be solved by using annotation verification.
For the usage of Annotation verification, please refer to: http://www.VeVB.COM/article/136448.htm
One thing to note here: InitBinder and Annotation can only choose one of two verifications. If InitBinder is used, Annotation verification cannot be used.
The previous configurations of web.xml and spring.xml will not be repeated, please refer to the configuration in the above link. Exactly the same.
Directly upload the code:
1. User5 model entity class
package com.my.controller.bean;import java.util.Date;public class User5 { private long id; private String name; private String password; private Date createTime; private int age; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public int getAge() { return age; } public void setAge(int age) { this.age = age; }}2. Add a new Validator:
package com.my.controller.validator;import org.springframework.stereotype.Component;import org.springframework.validation.Errors;import org.springframework.validation.ValidationUtils;import org.springframework.validation.Validator;import com.my.controller.bean.User5;@Componentpublic class TestValidator implements Validator { @Override public boolean supports(Class<?> paramClass) { return User5.class.equals(paramClass); } @Override public void validate(Object obj, Errors errors) { User5 user = (User5) obj; ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "valid.name", null, ""); if(user.getAge() < 18) { errors.rejectValue("age", "valid.ageMin", new Object[]{"age" ,18}, "Age cannot be less than {1} years old"); } }}@Component needs to be added here and DI is injected
3. Controller
package com.my.controller;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import javax.validation.Valid;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.stereotype.Controller;import org.springframework.validation.BindingResult;import org.springframework.validation.FieldError;import org.springframework.validation.Validator;import org.springframework.web.bind.WebDataBinder;import org.springframework.web.bind.annotation.InitBinder;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 com.my.controller.bean.User5;@Controller@RequestMapping(value="binder")public class TestInitBinderController { @Autowired @Qualifier(value="testValidator") private Validator validator; @InitBinder private void initBinder(WebDataBinder binder) { binder.setValidator(validator); } @RequestMapping(method=RequestMethod.GET) public String index() { return "/TestInitBinder/index"; } @RequestMapping(value="add", method=RequestMethod.POST) public ModelAndView add(@ModelAttribute @Valid User5 user, BindingResult result) { ModelAndView view = new ModelAndView("TestInitBinder/index"); view.addObject("user", user); if(result.hasErrors()) { List<FieldError> errs = result.getFieldErrors(); Map<String, String> mapErrors = new LinkedHashMap<String, String>(); for(FieldError err : errs) { System.out.println("ObjectName:" + err.getObjectName() + "/tFieldName:" + err.getField() + "/tFieldValue:" + err.getRejectedValue() + "/tMessage:" + err.getDefaultMessage()); mapErrors.put(err.getField(), err.getDefaultMessage()); view.addObject("errors", mapErrors); } return view; } return view; }}Inject Validator into the Controller.
In fact, using InitBinder, the err.getDefaultMessage() method in the add controller cannot get the corresponding correct message. You can see the final input print result.
4. View
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%><%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %><%@ taglib prefix="st" uri="http://www.springframework.org/tags" %><%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Init binder</title></head><body> <form:form action="/TestSpringMvc1/binder/add" method="post" modelAttribute="user5"> User name:<input type="text" id="name" name="name" value="${user.name}" /><br/> Password:<input type="text" id="password" name="password" value="${user.password}" /><br/> Age:<input type="text" id="age" name="age" value="${user.age}" /><br/> <input type="submit" value="Add"/> <hr/> Error:<br/> <form:errors path="*"></form:errors> </form:form></body></html>Note that you can only use <form:errors /> to obtain error information, and this <form:errors/> must be in <form:form/>.
5. Results Test
Click Add button:
Printout:
You can see that the correct information of the error cannot be obtained here
In fact, when the data submitted in a very complex form page has certain business logic, InitBinder should not be used much, because many times we can use a map to insert errors into it and read it on the page. for example:
Map<String, String> errors;
errors.add("name", "user name can NOT be empty!");
:
:
You only need to use:
<span style="color:red;">${errors.name}<span>Just do it.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.