Customize error messages using BindingResult

  • 2021-12-04 10:07:15
  • OfStack

Directory BindingResult Custom Error Message Premise Profile Basic Framework Configuration File and Modification of Java Code Specify verification required in Controller method for custom verification Display verification error message on JSP page BindingResult error return display failed

BindingResult Custom Error Messages

Premise summary

In the integration project of Spring, MVC and FreeMarker, JSR-303 validation framework is used to validate the data by annotation

Basic framework

MVC: Spring MVC 3 View: FreeMarker Verification: Hibernate-validator implementation

Modification of configuration file and Java code

Adding Configuration in Spring MVC Configuration File

Add the following annotation driver configuration of mvc, and 1 cut to "Automation"


<mvc:annotation-driven />  

Adding annotations to data validation in JavaBean

Among them, @ Length and @ email are the data verification annotations in Hibernate-validator, and the annotations in javax. validation can also be used, such as @ NotNull


public class SystemUser {  
    @Length(min = 5, max = 20, message = " User name length must be at 5 To 20 Between ")  
    private String userName;   
    @Email(message = " For example, enter the correct mailbox ")  
    private String email;  
}  

Specify that verification is required in the Controller method

First of all, add @ Valid annotation in front of Bean that needs to be verified, and tell SpringMVC framework that this Bean needs to be verified;

At the same time, add @ modelattribute annotation in front of Bean to be verified, so as to expose Bean to the view and specify the name, which has two functions. The first is to show that the verification error needs to use this name, and the second is to return to the original page, and all the values entered before will be displayed;

Secondly, each Bean to be verified is followed by an BindingResult, and the SpringMVC framework will save the verification results in it, and whether there are verification errors can be judged by hasErrors method;

Finally, after returning to the original page, the SpringMVC framework will also save all verification error information in the context for obtaining verification errors on the page. Spring provides a set of JSP custom tags.


@RequestMapping(value = "/create.html", method = RequestMethod.POST)  
public String doCreateUser(  
        @Valid @ModelAttribute("userDetail") SystemUser user,  
        BindingResult bindingResult,  
        HttpServletRequest request) {  
    //  If there are validation errors, return to the page of adding users   
    if (bindingResult.hasErrors()) {  
        return "/user/create";  
    }        
    this.userService.createUser(user);  
    return "/user/list.html";  
}  

Perform custom validation

If you need to add custom validation, such as verifying whether the user name has been used, then simple annotations are naturally powerless, and you need to code yourself. If the validation fails, you can manually add custom validation errors to BindingResult.


@RequestMapping(value = "/user/create.html", method = RequestMethod.POST)  
public String doCreateUser(  
        @Valid @ModelAttribute("userDetail") SystemUser user,  
        BindingResult bindingResult,  
        HttpServletRequest request) {  
    //  If there are data validation errors, return to the page of adding users   
    if (bindingResult.hasErrors()) {  
        return "/user/create";  
    }    
    boolean isUserNameExist = this.userService.checkUserByUserName(user.getUserName());  
    //  If the user name already exists, return to the page where you added the user   
    if (isUserNameExist) {  
        //  Toward BindingResult Add an existing validation error for the user   
        bindingResult.rejectValue("userName", " The user name already exists ", " The user name already exists ");  
        return "/user/create";  
    }        
    this.userService.createUser(user);  
    return "/user/list.html";  
}

Display validation error message on JSP page

After returning to the page, SpringMVC framework puts all verification error messages in the context and can take them out by itself, but that is very troublesome, but it doesn't matter. Spring provides a set of custom tags, which can easily display verification error messages.

The page header needs to import the custom tag library of Spring


<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>  

Need to display all verification errors once

(The value of commandName is the value specified in the @ modelattribute annotation)


<form:form commandName="userDetail"> 
<form:errors path="*" cssStyle="color:red"></form:errors> 
</form:form> 

You need to display a single validation error after the corresponding input box

(Specify which specific validation error to display through path, which is the value specified in the @ modelattribute annotation, followed by a validation error specifying which attribute in Bean to display.)


<input type="text" name="userName" value="${userDetail.userName}" > 
<form:errors path="userDetail.userName" cssStyle="color:red"></form:errors> 
<input type="text" name="email" value="${userDetail.email}"> 
<form:errors path="userDetail.email" cssStyle="color:red"></form:errors> 

BindingResult Error Return Display Failure

Being a beginner often makes low-level mistakes, especially without a teacher. I tripped all day, but I found the reason

If redirect jumps back and causes parameter loss

You can set the return parameter to Object


@RequestMapping(value = "/save", method = RequestMethod.POST)
public Object test(HttpServletRequest request, Model model, @Validated User user, BindingResult bindingResult)
throws Exception {
if (bindingResult.hasErrors()) {
return "user/save";
}
user.setVersion(0);
return new ModelAndView("redirect:/user/list");
}

Related articles: