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

Check the non-empty annotation @ NotNull how to get a custom message

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

Share

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

This article mainly introduces the check non-empty annotation @ NotNull how to obtain a custom message, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand.

Because the project form needs to check too many fields, it is too troublesome to check null one by one, so the @ NotNull annotation is used. If the field is empty, a MethodArgumentNotValidException exception will be thrown.

Next, you need to get the message content in @ NotNull (message= "custom exception") for the front end to display.

Paste the code directly:

Public String getMessage (MethodArgumentNotValidException exception) {String message = exception.getBindingResult () .getFieldError () .getDefaultMessage (); return message;} usage: define a global exception handling

Once such an exception occurs, it will capture and process it and return the information to the front end. The return class Result should be defined according to the business needs of your own project.

Simple use of annotations such as @ NotNull

The jar package will not be introduced automatically after springboot 2.3.0, so add the following maven

2.3 previously, there was no need to introduce the maven package org.springframework.boot spring-boot-starter-validation

Sign up for an account with account number and password

The front end will do a null call, but the back end will also do a null call to prevent direct url access.

At this point, the back-end code is usually

If (nameplate null) {return "account cannot be empty, please re-enter";} else if (passwordpassword null) {return "password cannot be empty, please re-enter";}

This will make it look very low and extremely ugly.

An annotation @ NotNull will be used at this point.

A simple example is given:

@ Datapublic class UserInfo {@ NotNull (message = "name cannot be null") private String name; @ Max (value = 30 Personality message = "Age cannot exceed 30") private Integer age; private Integer password; private String sex;} Controller layer

A simple example to illustrate

@ RestControllerpublic class TestController {@ RequestMapping ("test1") public Object test1 (@ Valid @ RequestBody UserInfo userInfo,BindingResult result) {/ / determine whether there is an abnormal error, and if so, return the default message if (result.hasErrors ()) {String defaultMessage = result.getFieldError (). GetDefaultMessage (); return defaultMessage;} / / print the data structure System.out.println (userInfo) / / if there is no error, return return "registered successfully";}}

Pass the json parameter with postMan. Name has a value, and the age is over 30 years old.

Return to our settings

Name is the same as null and will be judged in order!

But here comes the question: do we have to write a judgment method in each Controller layer's method?

Of course not, the global exception class will be used at this time.

Set up a class

@ ControllerAdvicepublic class ControllerException {@ ResponseBody @ ExceptionHandler (MethodArgumentNotValidException.class) public Object handleValidException (MethodArgumentNotValidException e) {/ / return the error message to the foreground return e.getBindingResult (). GetFieldError (). GetDefaultMessage ();}}

To make a difference, write down another access method

@ RequestMapping ("test2") public Object test1 (@ Valid @ RequestBody UserInfo userInfo) {System.out.println (userInfo); return "registered successfully";}

At this point, we pass in parameters.

At this point, you don't have to write a bunch of short judgments anymore.

Some notes are attached.

@ Null limit can only be null

@ NotNull restriction must not be null

@ AssertFalse limit must be false

@ AssertTrue limit must be true

The @ DecimalMax (value) limit must be a number not greater than the specified value

The @ DecimalMin (value) limit must be a number not less than the specified value

@ Digits (integer,fraction) limit must be a decimal, and the number of digits in the integer part cannot exceed integer, and the number of digits in the decimal part cannot exceed fraction

The @ Future restriction must be a future date

The @ Max (value) limit must be a number not greater than the specified value

The @ Min (value) limit must be a number not less than the specified value

The @ Past restriction must be a past date

The @ Pattern (value) restriction must conform to the specified regular expression

@ Size (max,min) limit character length must be between min and max

@ Past validates that the element value (date type) of the annotation is earlier than the current time

@ NotEmpty verifies that the element value of the annotation is not null and is not empty (string length is not 0, collection size is not 0)

@ NotBlank verifies that the element value of the annotation is not empty (not null, and the length is 0 after removing the first space), unlike @ NotEmpty,@NotBlank, which only applies to strings and removes string spaces when comparing

@ Email verifies that the element value of the annotation is Email, or you can specify a custom email format through regular expressions and flag

Second update: all Controller code written in this way should be encapsulated into exception classes

Import org.springframework.web.bind.MethodArgumentNotValidException;import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.ResponseBody;/** * @ author: lsy * @ date: Created in 2020-7-23 10:13 * @ modified By: * / @ ControllerAdvicepublic class ControllerException {private final static String EXCEPTION_MSG_KEY = "Exception message:" @ ResponseBody @ ExceptionHandler (MethodArgumentNotValidException.class) public Object handleValidException (MethodArgumentNotValidException e) {/ / log error messages / / log.error (Objects.requireNonNull (e.getBindingResult (). GetFieldError ()). GetDefaultMessage ()); / / return the error message to the foreground / / return BaseResult.fail (500, Objects.requireNonNull (e.getBindingResult (). GetFieldError ()). GetDefaultMessage ()) Return e.getBindingResult (). GetFieldError (). GetDefaultMessage ();}

You don't need to write BindingResult to return message

Thank you for reading this article carefully. I hope the article "verifying non-empty annotations @ NotNull how to get custom message" shared by the editor is helpful to everyone. At the same time, I also hope you can support us and follow the industry information channel. More related knowledge is waiting for you to learn!

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