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 understand how SpringBoot interface receives json parameters

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

Share

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

This article focuses on "how to understand the SpringBoot interface to receive json parameters", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "how to understand how the SpringBoot interface receives json parameters".

Preface of SpringBoot interface receiving json parameters

Generally speaking, HTTP methods are mapped to CRUD actions, but this is not a strict restriction. Sometimes PUT can be used to create new resources, and POST can also be used to update resources. So in normal Web development, you may often see that the values of method are GET and POST, but we need to develop a good coding habit.

CRUD action HTTP method CreatePOSTReadGETUpdatePUT (all resources) or PATCH (partial resources) DeleteDELETE premise

First add a note to controller: @ RestController

@ RestController@RequestMapping ("/ user") @ Api (tags = "user", description = "user controller") public class UserController {/ /.}

Detailed introduction

1. GET

1) @ PathVariable gets the path parameters. This form is url/ {id}.

@ GetMapping ("/ getDetail/ {id}") @ ApiOperation (value = "get the user according to id") public RbacUser getDetail (@ PathVariable Long id) {return userService.getById (id);}

2) @ RequestParam to get the query parameters. In the form of url?name=xx

The main parameters are:

Value: parameter name, that is, the request parameter name of the input parameter. For example, username indicates that the value of the parameter whose name is username in the request parameter area will be passed

Required: whether it is required. The default is true, which means there must be a corresponding parameter in the request, otherwise an error will be reported.

@ GetMapping ("/ getByAccount") @ ApiOperation (value = "get users based on account") public RbacUser getByAccount (@ RequestParam (required = false) String account) {return userService.getByAccount (account);}

3) directly encapsulate the DTO parameter form

@ GetMapping ("/ find") @ ApiOperation (value = "get users according to conditions") public List find (RbacUserDTO rbacUserDTO) {return userService.find (rbacUserDTO);} II. DELETE

@ PathVariable gets the path parameter. This form is url/ {id}.

@ DeleteMapping ("/ delete/ {id}") @ ApiOperation (value = "delete user") public void delete (@ PathVariable Long id) {userService.delete (id);} III. POST/PUT/PATCH

@ RequestBody inserts the HTTP request body into the method and writes the request body to an object using the appropriate HttpMessageConverter.

@ PostMapping ("/ create") @ ApiOperation (value = "create user") public RbacUser getByAccount (@ RequestBody @ Validated RbacUserDTO rbacUserDTO) {return userService.save (rbacUserDTO);}

@ Validated: check the data. The error report of the following comments will be returned directly. If the verification class contains an object reference attribute, you need to add @ Valid to the attribute.

For specific parameter tests, please refer to the following

Overview of Springboot restFul Parameter Test

Check the request parameters, which is often encountered in web. If you use each if/else to judge, it is believed that the readability of such code will be relatively poor.

JSR-303 is the standard framework provided by java for validating the validity of bean data. It is a sub-specification in Java EE6, called BeanValidation. JSR303 specifies the verification rules by annotating @ NotNull, @ Max and other standards on the Bean attribute, and validates Bean through the verification interfaces of these standards.

Specify that some verification specifications, such as @ Null, @ NotNull, @ Pattern, are located under the javax.validation.constraints package and provide only the specification but not the implementation.

In Spring, there are two ways to validate input, one is to use the verification framework that comes with Spring, and the other is to use the implementation of JSR-303. It is generally recommended to use the implementation of JSR-303, such as Hibernate-Validator.

Hibernate-Validator is the implementation of JSR-303. Hibernate Validator provides an implementation of all the built-in constraint in the JSR-303 specification, in addition to some additional constraint, such as @ Email, @ Length, @ Range, and so on, under the org.hibernate,validator.constraints package.

There is already a hibernate-vlidator package in the spring-boot-starter-web package, so there is no need for additional references to hibernate validator dependencies.

At the same time, in order to provide convenience for developers, Spring encapsulates Hibernate-Validator twice and encapsulates LocalValidatorFactorBean as the implementation of validator. This class is compatible with Spring's Validation system and Hibernate's Validation system, and LocalValidatorFactorBean has become the default implementation of Validator.

Description: JSR-349 is an upgraded version of JSR-303, with some new features added

As shown in the figure below, this is the hibernate dependency in spring boot 2.1.1:

An example of commonly used annotation attribute description @ AssertTrue is applied to the boolean attribute, which must be true

@ AssertTrue

Boolean isOkay

@ AssertFalse is applied to the boolean attribute, which must be false

@ AssertFalse

Boolean isOkay

@ DecimalMax can only be less than or equal to the specified value

@ DecimalMax ("1.1")

BigDecimal price

@ DecimalMin can only be greater than or equal to the specified value

@ DecimalMin ("1.1")

BigDecimal price

@ Digits the attribute value must be within the specified range, the interger attribute defines the maximum integer part of the value, and the fraction attribute defines the maximum decimal part of the value.

@ Digits (integer=5, fraction=2)

BigDecimal price

@ Future checks whether the field belongs to a future date

@ Future

Date shippingDate

@ Max the value of this field can only be less than or equal to this value

@ Max (20)

Int age

@ Min the value of this field can only be greater than or equal to this value

@ Min (20)

Int age

@ NotNull this field cannot be Null

@ NotNull

String name

@ Null this field must be Null

@ Null

String dest

@ Past this field must be a past date

@ Past

Date birthDate

@ Size checks whether the size of this field is between min and max, which can be string, array, collection, Map, etc.

@ Size (min=2, max=10)

String description

@ Pattern the value of this property must match the specified regular expression

@ Pattern (regexp= "\\ d {3}")

String areaCode

@ NotBlank is for String only, cannot be Null and size > 0 after trim ()

@ NotBlank

String src

@ NotEmpty cannot be Null and size > 0

@ NotEmpty

String src

@ Email the annotated element must be an email address

@ Length the String size of the commented string must be within the specified range

@ Length (min=6, max=12, message= "password length must be 6x12")

String src

@ RangeBigDecimal,BigInteger,CharSequence, byte, short, int, long and other atomic types and wrapper types, verify that the element value of the annotation is between the minimum value and the maximum value

@ Valid

Specify the object associated with recursive validation (discussed in the next section)

If there is an address object attribute in the user object, if you want to verify the address object together when verifying the user object, add the @ Valid annotation to the address object to cascade the verification.

Simple application examples

Bean definition to be verified:

Public class StudentBean implements Serializable {@ NotBlank (message = "user name cannot be empty") private String name; @ Min (value = 18, message = "age cannot be less than 18") private Integer age @ Pattern (regexp = "^ ((13 [0-9])) | (14 [5meme 7meme 9]) | (15 ([0-3] | [5-9])) | (166) | (17 [0-9]) | (18 [0-9]) | (19 [8 | 9])\ d {8} $", message = "incorrect Mobile number format") private String phoneNum; @ Email (message = "incorrect mailbox format") Public String getName () {return name;} public void setName (String name) {this.name = name;} public Integer getAge () {return age;} public void setAge (Integer age) {this.age = age;} public String getPhoneNum () {return phoneNum;} public void setPhoneNum (String phoneNum) {this.phoneNum = phoneNum } public String getEmail () {return email;} public void setEmail (String email) {this.email = email;}}

Return the error field definition:

Public class ArgumentsInvalidResponseBean {private String argumentName; private String exceptionMsg; public ArgumentsInvalidResponseBean () {} public ArgumentsInvalidResponseBean (String argumentName, String exceptionMsg) {this.argumentName = argumentName; this.exceptionMsg = exceptionMsg;} public String getArgumentName () {return argumentName;} public void setArgumentName (String argumentName) {this.argumentName = argumentName;} public String getExceptionMsg () {return exceptionMsg } public void setExceptionMsg (String exceptionMsg) {this.exceptionMsg = exceptionMsg;}}

Global exception handling:

@ ExceptionHandler (MethodArgumentNotValidException.class) @ ResponseBody public List methodArgumentNotValidExceptionHandler (MethodArgumentNotValidException ex) {System.out.println ("= methodArgumentNotValidExceptionHandler Occur="); List argumentsInvalidResponseBeanList = new ArrayList (); for (FieldError error: ex.getBindingResult (). GetFieldErrors ()) {ArgumentsInvalidResponseBean bean = new ArgumentsInvalidResponseBean (); bean.setArgumentName (error.getField ()); bean.setExceptionMsg (error.getDefaultMessage ()); argumentsInvalidResponseBeanList.add (bean) } return argumentsInvalidResponseBeanList;}

Test the code:

RestControllerpublic class CheckController {@ PostMapping ("stu") public String addStu (@ Valid @ RequestBody StudentBean studentBean) {return "add student success";}}

Test in PostMan:

Note that there is an error in age and mailbox. Check the returned value after running, as shown below:

Custom check

Create a new annotation class MyConstraint:

@ Target ({ElementType.METHOD, ElementType.FIELD}) @ Retention (RetentionPolicy.RUNTIME) @ Constraint (validatedBy = MyConstraintValidator.class) public @ interface MyConstraint {String message () default "this is a custom comment to detect whether input is uppercase"; Class [] groups () default {}; Class

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