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

The method of handling parameters of Common get/post requests in SpringBoot

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

Share

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

This article mainly introduces the relevant knowledge of SpringBoot common get/post request parameter processing methods, the content is detailed and easy to understand, the operation is simple and fast, and has a certain reference value. I believe you will gain something after reading this article on the handling of common get/post request parameters in SpringBoot. Let's take a look at it.

Spring boot common http get, post request parameter processing

When defining a Rest interface, GET, POST, PUT and DELETE are usually used to add, delete, modify and query data. Some of these methods need to pass parameters, and background developers must verify the parameters received to ensure the robustness of the program.

GET

Generally used for querying data, transmitting in clear text, and generally used to obtain some data that has nothing to do with user information.

POST

Commonly used to insert data

PUT

Generally used for data update

DELETE

Commonly used for data deletion

Logical deletion is generally performed (that is, only changing the state of the record rather than actually deleting the data)

@ PathVaribale gets the data in url

@ RequestParam gets the value of the request parameter

@ GetMapping combined annotation, which is an abbreviation for @ RequestMapping (method = RequestMethod.GET)

@ RequestBody uses an object to get the data sent from the front end

PathVaribale gets the data of url path

Request URL:

Localhost:8080/hello/id gets id value

The implementation code is as follows:

@ RestControllerpublic class HelloController {@ RequestMapping (value= "/ hello/ {id} / {name}", method= RequestMethod.GET) public String sayHello (@ PathVariable ("id") Integer id,@PathVariable ("name") String name) {return "id:" + id+ "name:" + name;}}

Enter the address in the browser:

Localhost:8080/hello/100/hello

Output:

Id:81name:hello

RequestParam gets the value of the request parameter

Get the url parameter value. By default, the method parameter name is required to be consistent with the url parameter.

Localhost:8080/hello?id=1000

RestControllerpublic class HelloController {@ RequestMapping (value= "/ hello", method= RequestMethod.GET) public String sayHello (@ RequestParam Integer id) {return "id:" + id;}}

Output:

Id:100

When there are multiple parameters in url, such as:

Localhost:8080/hello?id=98&&name=helloworld

The specific code is as follows:

@ RestControllerpublic class HelloController {@ RequestMapping (value= "/ hello", method= RequestMethod.GET) public String sayHello (@ RequestParam Integer id,@RequestParam String name) {return "id:" + id+ "name:" + name;}}

Get the url parameter value and execute the parameter name method

Localhost:8080/hello?userId=1000

@ RestControllerpublic class HelloController {@ RequestMapping (value= "/ hello", method= RequestMethod.GET) public String sayHello (@ RequestParam ("userId") Integer id) {return "id:" + id;}}

Output:

Id:100

Be careful

If you do not enter a specific value for id, the result returned is null. The specific test results are as follows:

Id:null

If you do not enter the id parameter, the following error will be reported:

Whitelable Error Page error

GET parameter check

Usage: use the default value when not entering id

The specific code is as follows:

Localhost:8080/hello

@ RestControllerpublic class HelloController {@ RequestMapping (value= "/ hello", method= RequestMethod.GET) / / required=false indicates that there can be no id parameter in url. The default parameter public String sayHello (@ RequestParam (value= "id", required=false, defaultValue = "1") Integer id) {return "id:" + id;}} is used.

Output

Id:1

POST JSON parameter check

Commonly used check notes

Note:

The parameters received are all of string type by default

Some annotations can only be used on attributes of type String

@ JsonProperty can solve the problem that the property names of the front end are inconsistent with those of the background entity class.

Check method:

Use @ RequestBody @ Valid to get and verify the JSON parameter.

Get the verification result through BindingResult bindingResult.

BindingResult source code:

Tip 01: use the hasErrors method of the BindingResult object to determine whether there is a parameter error

Tip 02: use the getFieldErrors method of the BindingResult object to get all the properties with parameter errors

Tip 03: use the getDefaultMessage of the error property object to get the error message

RequestMapping (value = "/ demo5", produces = MediaType.TEXT_PLAIN_VALUE) @ ResponseBody public String test5 (@ RequestBody @ Valid User user, BindingResult bindingResult) {if (bindingResult.hasErrors ()) {List objectErrors = bindingResult.getAllErrors (); System.out.println (objectErrors.toString ()); for (ObjectError objectError: objectErrors) {System.out.println ("objectError =" + objectError.getObjectName ()) System.out.println ("objectError =" + objectError.getDefaultMessage ()); System.out.println ("objectError =" + objectError.getCode ()); System.out.println ("objectError =" + objectError.getArguments ());}} String str = user.toString (); return str;}

Corresponding User entity class code:

Public class User {@ NotEmpty (message = "ID cannot be empty") @ NotBlank (message = "ID cannot be empty") private String id; @ Min (value = 18) @ Max (value = 30) private Integer age @ NotEmpty (message = "nickname cannot be empty") @ NotBlank (message = "nickname cannot be empty") @ JsonProperty ("nickname") / / when the current end property is nick background receiving object's property is nickName, you can use @ JsonProperty to maintain consistent private String name;. Omit the custom annotation check of get set method

1. Define a check comment

The code is as follows:

Import javax.validation.Constraint;import javax.validation.Payload;import java.lang.annotation.*;@Documented@Retention (RetentionPolicy.RUNTIME) @ Target ({ElementType.PARAMETER, ElementType.FIELD}) @ Constraint (validatedBy = MyFormValidatorClass.class) public @ interface MyFormValidator {String value (); String message () default "name can be test"; 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