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

Example Analysis of Spring Validator Interface check and Global exception Handler

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly shows you "Spring Validator interface verification and sample analysis of global exception handlers", which is easy to understand and well-organized. I hope it can help you solve your doubts. Let me lead you to study and learn the article "Spring Validator interface verification and sample analysis of global exception handlers".

Spring Validator interface check

The log uses the Bean Validation verification mechanism to verify the basic data types by using annotations to identify the verification method on the attributes of the entity class, and finally add the @ Vlidated annotation to the formal parameters of the specific method in the Controller class. One disadvantage of Bean Validation validation is that our data validation is constrained in the Java entity class, if we have multiple processor methods that need to use the same entity class, then the verification rules defined on the entity class attributes are difficult to divide, some processors only need to verify one attribute, while some processors need to verify multiple attributes, we can not create an entity class for each processor. The solution is also mentioned in the previous log that we can use packet verification. In addition, we can also use Spring's Validator interface to verify, which allows us to specify the verification rules of an object externally.

Validator implementation class

Spring's Validator is an interface, and our own verification implementation class must implement this interface before we can complete the custom verification rules by rewriting methods. There are two methods that we need to implement: supports () and validate ().

Public class UserValidator implements Validator {@ Override public boolean supports (Class clazz) {/ / reflection mechanism obtains the instance return User.class.equals (clazz) of the class through the class static variable of the class } @ Override public void validate (Object obj, Errors errors) {/ / error message is put in the errors object ValidationUtils.rejectIfEmpty (errors, "username", "Username.is.empty", "user name is not allowed to be empty.") ; User user = (User) obj; if (user.getPassword () = = null | | user.getPassword () .equals (")) {/ / rejectValue () Parameter: error field name, global error code, default error message errors.rejectValue (" password "," Password.is.empty "," password is not allowed to be empty. ") ;} else if (user.getPassword (). Length () < 8) {errors.rejectValue ("password", "Length.too.short", "password length cannot be less than eight digits.") ;}

The function of the Support () method is to determine whether the parity class supports the validated entity class. For example, our verification class is responsible for verifying the User class. The supports () method passes in the verified entity class, obtains the instance of the User class through the reflection mechanism, and then determines whether it matches the incoming verified entity class. The Validate () method is the concrete implementation of the verification. There is an Errors object in the method parameter list, which is responsible for storing the error information of the check. Here are the specific verification rules. We can use the method of the ValidationUtils verification tool class to verify. The parameters provided are error, the field name of the verification (for the attributes in the verification entity class), and the global error code (similar to the error message of using external properties according to the error code in Bean Validation verification). The last parameter is the default error message. When the global error code does not find the corresponding message, the default error message is used.

In addition to using the ValidationUtils validation utility class, line 23 can also use the methods of the erroe object to set to get the validation error message, and the parameters are almost the same as the methods of the ValidationUtils class.

Controller implementation class

After the validator class is configured, it is used in the specific business logic processing part of the Controller class.

@ Controller@RequestMapping ("user") public class InterfaceValidationController {@ InitBinder public void initBinder (DataBinder binder) {/ / set the Validator check interface binder.setValidator (new UserValidator ()) for DataBinder objects;} @ RequestMapping ("login") public String login (Model model, @ Valid User user, BindingResult result) {List allErrors = null If (result.hasErrors ()) {allErrors = result.getAllErrors () / / output all error messages for (ObjectError objectError: allErrors) {System.out.println ("code =" + objectError.getCode () + "DefaultMessage =" + objectError.getDefaultMessage ()) / / send the error message to the front-end page model.addAttribute ("allErrors", allErrors);} / / finally return the view return "users/login" } else {/ / if there is no error in the verification, jump to the successfully logged in page return "users/successLogin";}}

First of all, we need to bind the validator in the Controller class method through the initBinder () method, which requires DataBinder object parameters. The function of the DataBinder object is to bind the data, convert the data, set the validator and so on. DataBinder has a member variable BindingResult, which is data-bound and validator-bound. When there is an error message in the check data, it will be put into the Errors property in the BindingResult object. As mentioned earlier in the Errors object collection, it is used to store error information. Add @ Valid annotation to the User class of the data object to be verified in the parameter list of the Controller specific method, identify the data object to be validated, and then add the BindingResult object (it is important to note here that the position of the BindingResult parameter must be immediately following the validated data object). When an error message occurs in the verification, line 15 can determine whether the verification is wrong by the hasErrors () method of the object Then use the getAllErrors () method to get the error message for output. Finally, in line 22, we send the error message to the front page for display and give the user a hint.

Front-end page test

Finally, do a simple login test on the front page:

Login interface user name: password: ${error.defaultMessage}

Line 15 iterates through the collection of allErrors error messages sent from the background and displays an error message if a verification error occurs. According to our previous validator configuration, neither the user name nor password is allowed to be empty for data validation of User class objects:

When the input information is correct, the user name and password are not empty, and the password length is not less than 8 digits, you can jump successfully:

Global exception handler Exception Resolver

For the error message when the program is running, we can check the log to troubleshoot the error. When we send the error message to the front-end page, in order to let the user understand the cause of the error, we need to deal with the error message and capture the information before it is sent to the front-end page. To complete the error message capture and processing, we need to configure our exception handler. The exception handler is used to define how to parse the exception when the program is running. It needs to customize the exception class, which stores the exception information corresponding to the exception. You also need to configure the exception handler. For the caught exception, if it is the expected exception configured in the custom exception class, the corresponding error message is thrown, otherwise, other display is performed.

Custom exception class

The first is the custom exception class. For example, we define an exception class and exception handler that handle the User class. In the exception class, we set the error information storage when an exception occurs in the User class.

Package com.mvc.exception; public class UserException extends Exception {private static final long serialVersionUID = 1L; private String exceptionMessage; public UserException (String exceptionMessage) {super (exceptionMessage); this.exceptionMessage = exceptionMessage;} public String getExceptionMessage () {return exceptionMessage } public void setExceptionMessage (String exceptionMessage) {this.exceptionMessage = exceptionMessage;}}

The custom exception class UserException is specifically responsible for handling User class exceptions. How does it specify to handle User classes? This is done in the exception handler, and UserException inherits the Exception class so that we can throw the exception in its throws in the concrete Controller method. An exception information variable is defined in this class, which is used to store the exception information. When the exception handler catches the exception of the User class, it sets the exception information through the construction method of UserException, and finally throws the UserException.

Exception handler

When it comes to the configuration of the exception handler, the exception handler is the core of catching and handling exceptions. In Spring MVC, the underlying exception will be thrown up level by level, and finally reach the global exception handler. The work of the global exception handler mainly has four steps:

Catch the exception and parse the exception type.

If the exception is an expected exception (there is a defined exception class), the corresponding exception information is thrown.

If the exception is not the expected exception, create a custom exception class and throw the corresponding exception information (such as "unknown exception information").

Bind the exception information to the front-end page and jump to the corresponding exception information page.

Combined with the custom exception class above, take a look at the configuration of the exception handler for the User class:

Package com.mvc.exception; import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.web.servlet.HandlerExceptionResolver;import org.springframework.web.servlet.ModelAndView; public class UserExceptionResolver implements HandlerExceptionResolver {@ Override public ModelAndView resolveException (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {/ / first parses the exception type UserException userException = null If (ex instanceof UserException) {/ / if the exception type is UserException, create the exception information userException = (UserException) ex of that type directly } else {/ / otherwise create a custom exception type userException = new UserException ("unknown error occurred.") ;} / / take out the error message String errorMessage = userException.getExceptionMessage (); ModelAndView modelAndView = new ModelAndView (); / / send the error message to the front-end page modelAndView.addObject ("errorMessage", errorMessage) / / directed to the error page modelAndView.setViewName ("errorPage/userError"); return modelAndView;}}

In Spring MVC, the exception information is finally handled by the global exception handler through DispatcherServlet, which requires the global exception handler to implement the HandlerExceptionResolver interface connection and rewrite the resolverException () method to complete the exception handling. There are two parameters to note in this method. Object handler specifies the object to be handled by the exception handler, and Exception ex obviously receives the exception thrown by the underlying layer.

In our exception handler UserExceptionResolver, line 14 first determines whether the exception type is the expected exception UserException we defined, and if so, throws it, otherwise, creates a custom exception type and gives the error message "unknown error". Finally, line 26, after the exception information is processed, it is sent to the front-end page for display and jumps to the error prompt interface.

Test case

Finally, to use our exception handler, first add this exception handler to the Spring configuration file:

Then make the corresponding judgment in the Controller class method, and if an expected exception occurs, throw:

@ Controller@RequestMapping ("user") public class InterfaceValidationController {@ InitBinder public void initBinder (DataBinder binder) {/ / set the Validator check interface binder.setValidator (new UserValidator ()) for the DataBinder object } @ RequestMapping ("login") public String login (Model model, @ Valid User user, BindingResult result) throws UserException {boolean allowVisit = checkUser (user) If (! allowVisit) {/ / the user does not have access rights and throws an exception throw new UserException ("you do not have access!") ;} List allErrors = null; if (result.hasErrors ()) {allErrors = result.getAllErrors () / / output all error messages for (ObjectError objectError: allErrors) {System.out.println ("code =" + objectError.getCode () + "DefaultMessage =" + objectError.getDefaultMessage ()) / / send the error message to the front-end page model.addAttribute ("allErrors", allErrors);} / / finally return the view return "users/login" } else {/ / if there is no error in the verification, jump to the successfully logged in page return "users/successLogin";}}

You can see line 57 and finally we will jump to the error page to display the error message:

The error indicates that an exception occurred. The error message is as follows: ${errorMessage}

These are all the contents of the article "Spring Validator Interface Verification and sample Analysis of Global exception handlers". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

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