Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to customize error messages using BindingResult

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the relevant knowledge of "how to use BindingResult custom error information". In the actual case operation process, many people will encounter such difficulties. Next, let Xiaobian lead you to learn how to handle these situations! I hope you can read carefully and learn something!

directory

BindingResult custom error message

Summary of premises

base frame

Modifications to configuration files and Java code

Specify validation required in Controller method

Perform custom validation

Display validation error messages on JSP pages

BindingResult error returns display failure

BindingResult custom error message premise summary

In the Spring MVC and FreeMarker integration project, JSR-303 validation framework is used to validate data through annotations.

base frame

MVC:Spring MVC 3

View from FreeMarker

Verification: Hibernate-validator implementation

Modifications to configuration files and Java code

Add configuration to Spring MVC configuration file

Add the following mvc annotation driven configuration and everything becomes "automated"

Adding Data Validation Annotations to JavaBeans

Where @Length and @email are the data validation annotations in Hibernate-validator, you can also use the annotations in javax.validation, such as @NotNull

public class SystemUser { @Length(min = 5, max = 20, message = "Username length must be between 5 and 20") private String userName; @Email(message = "Enter the correct email address") private String email; } Specify validation required in Controller method

First, add @Valid annotation in front of Bean that needs validation, telling SpringMVC framework that Bean needs validation;

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

Secondly, each Bean that needs to be verified is followed by a BindingResult. The SpringMVC framework will store the verification result in it. The hasErrors method can determine whether there is a verification error.

Finally, when returning to the original page, the Spring MVC framework also saves all validation error messages in context for the page to retrieve validation errors. 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 is a verification error, return to the add user page if (bindingResult.hasErrors()) { return "/user/create"; } this.userService.createUser(user); return "/user/list.html"; } Perform custom validation

If you need to add a custom check, such as verifying whether the user name has been used, then simple comments are naturally powerless and need to be coded by yourself. If the check fails, you can manually add the custom check error to BindingResult.

@RequestMapping(value = "/user/create.html", method = RequestMethod.POST) public String doCreateUser( @Valid @ModelAttribute("userDetail") SystemUser user, BindingResult bindingResult, HttpServletRequest request) { //If there is a data verification error, return to the page where you add users if (bindingResult.hasErrors()) { return "/user/create"; } boolean isUserNameExist = this.userService.checkUserByUserName(user.getUserName()); //If the username already exists, return to the page where you added the user if (isUserNameExist) { //Add existing validation error for user to BindingResult bindingResult.rejectValue("userName", "This username already exists", "This username already exists"); return "/user/create"; } this.userService.createUser(user); return "/user/list.html"; } Display validation error messages on JSP pages

After returning to the page, SpringMVC framework will be all check error information in the context, you can get it yourself, but that is very troublesome, but it does not matter, Spring provides a set of custom tags, you can easily display check error information.

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

All verification errors need to be displayed at once

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

A single check error needs to be displayed after the corresponding input box

(Specify which specific validation error to display by path, userDetail is exactly the value specified in the @modelattribute annotation, and the dot is followed by the validation error specifying which attribute in the Bean to display)

BindingResult error returns display failure

Being a beginner often makes mistakes, especially when there is no teacher. I tripped all day, but I figured out why.

If redirect jumps back causes parameter loss

At this time, you can set the return parameter to Object

@RequestMapping(value = "/save", method = RequestMethod.POST)public Object test(HttpServletRequest request, Model model, @Validated User, BindingResult bindingResult)throws Exception {if (bindingResult.hasErrors()) {return "user/save";}user.setVersion(0);return new ModelAndView("redirect:/user/list");}"How to customize error messages using BindingResult" is introduced here. Thank you for reading. If you want to know more about industry-related knowledge, you can pay attention to the website. Xiaobian will output more high-quality practical articles for everyone!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report