spring boot Common http Request url Parameter Acquisition Method

  • 2021-09-05 00:00:24
  • OfStack

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

GET: 1 is used to query data and transmit it in clear text. 1 is used to obtain data that has nothing to do with user information POST: 1 is used to insert data PUT: 1 for data updates DELETE: 1 is generally used for data deletion; 1 is usually logical deletion (that is, only changing the state of records, not actually deleting data)

1. @ PathVaribale gets the data in url

Request URL: localhost:8080/hello/id 获取id值

The implementation code is as follows:


@RestController
publicclass 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

2. @ RequestParam Get the value of the request parameter

Obtain the value of url parameter, the default mode, the method parameter name and url parameter are required to keep 1

Request URL: localhost:8080/hello?id=1000


@RestController
publicclass 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:


@RestController
publicclass 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 mode

localhost:8080/hello?userId=1000


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

Output:

id: 100


Related articles: