Summary of interaction between client and springboot REST interface parameter @ RequestParam @RequestBody

@Parameters of RequestParam annotation

Default behavior

Nothing is added in front of the parameter. The default function is @ RequestParam. However, ensure that the requested parameter name is consistent with the received parameter name

For example:
Send an ajax request in an html page with a parameter named p

<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<title>parameter</title>
</head>
<body>

<!-- <a href="http://192.168.8.175:8087 / test / param "> a tag connection < / a > -- >
<p>========================</p>
<input type="submit" onclick="ajaxsubmit()" value = "ajax Submit"/>

<script type="text/javascript">
	
	function ajaxsubmit () {
		var jsond = {
				param1 : 'aaa',
				param2 : 'bbb',
				param3 : 'ccc'
			}
		
		$.ajax({
			url:"http://192.168.8.175:8087/test/param?p=313",
			type:"post",
// 			Data: json. Stringify (json d), / / convert json objects into json strings
// 			data:jsond,
// 			dataType:"json",
// 			contentType : "application/json;charset=UTF-8",
			success:function(result) {	
				// doSomething
				console.log(result);
			}
		});
	}
	
</script>
</body>
</html>

The parameter of the parameter receiver must also contain p

import java.io.BufferedReader;

import javax.servlet.http.HttpServletRequest;

import org.bouncycastle.util.encoders.BufferedDecoder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RequestParamController {
	
	@PostMapping("/test/param")
	@CrossOrigin
	public String paramTest(String p) {
		System.out.println("p="+p);
		return p;
	}
	
}

Test:

If @ RequestParam annotation is added, the parameter name does not have to be the same, but the value of @ RequestParam annotation must be consistent with the requested parameter name:

import java.io.BufferedReader;

import javax.servlet.http.HttpServletRequest;

import org.bouncycastle.util.encoders.BufferedDecoder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RequestParamController {
	
	@PostMapping("/test/param")
	@CrossOrigin
	public String paramTest(@RequestParam("p") String pxxxxx) {
		System.out.println("p="+pxxxxx);
		return pxxxxx;
	}
	
}

@The parameters of the RequestParam annotation receive request parameters in the form of key value pairs

Key value pair format parameter requests include:

1. Parameters spliced after URL address:

$.ajax({
   		url:"http://192.168.8.175:8087/test/param?p=313",
   		type:"post",
// 			Data: json. Stringify (json d), / / convert json objects into json strings
// 			data:jsond,
// 			dataType:"json",
// 			contentType : "application/json;charset=UTF-8",
   		success:function(result) {	
   			// doSomething
   			console.log(result);
   		}
   	});

Here p=313 is a key value pair;

<a href="http://192.168.8.175:8087 / test / param? P = 111 & P2 = 222 "> a label connection</a>

Here, P = 111 & p2 = 222 represent two key value pairs, and the receiver needs two parameters p and p2 respectively

2. Parameters of form submission

Requestor:

Receiver:

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RequestParamController {
	
	@PostMapping("/test/param")
	@CrossOrigin
	public String paramTest(String param1,String param2,String param3) {
		return param1+param2+param3;
	}
	
}

3. The requestor parameter is a json object

<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<title>parameter</title>
</head>
<body>

<!-- <a href="http://192.168.8.175:8087 / test / param? P = 111 & P2 = 222 "> a label connection < / a > -- >
<p>========================</p>
<input type="submit" onclick="ajaxsubmit()" value = "ajax Submit"/>

<script type="text/javascript">
	
	function ajaxsubmit () {
		var jsond = {
				param1 : 'a1',
				param2 : 'b2',
				param3 : 'c3'
			}
		
		$.ajax({
			url:"http://192.168.8.175:8087/test/param",
			type:"post",
// 			Data: json. Stringify (json), / / convert the json object into a json string, and the parameters passed are json strings
			data:jsond, // The parameters passed are json objects
			dataType:"text",
// 			contentType : "application/json;charset=UTF-8",
			success:function(result) {	
				// doSomething
				console.log(result);
			}
		});
	}
	
</script>
</body>
</html>

Note: data: json represents json object, and * * data: json. Stringify (json) * * represents json string

  • The essence of json object is a key value pair, so the receiver can use @ RequestParam (not added by default) to receive.
  • The essence of json strings is strings (nonsense!).

The receiver uses @ requestparam (not added by default)

package com.omomcam.controller.ca;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RequestParamController {
	
	@PostMapping("/test/param")
	@CrossOrigin
	public String paramTest(String param1,String param2,String param3) {
		return param1+param2+param3;
	}
	
}

Note: because the receiver here is a directly returned String string, the dataType of ajax in the sender: "text", which should be text, can be matched and received normally.

Test:

In a word, as long as it is a request parameter in the form of key value pair, the receiver can use @ RequestParam to receive it (not added by default), including file upload, which can be referred to https://blog.csdn.net/qq_29025955/article/details/111318994 As long as it's a key value pair.

Multiple @ RequestParam parameters can be encapsulated into a java object to receive request parameters

Receiver parameter encapsulation class:

public class TestParamEntity {
	
	private String param1;
	private String param2;
	private String param3;
	public String getParam1() {
		return param1;
	}
	public void setParam1(String param1) {
		this.param1 = param1;
	}
	public String getParam2() {
		return param2;
	}
	public void setParam2(String param2) {
		this.param2 = param2;
	}
	public String getParam3() {
		return param3;
	}
	public void setParam3(String param3) {
		this.param3 = param3;
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((param1 == null) ? 0 : param1.hashCode());
		result = prime * result + ((param2 == null) ? 0 : param2.hashCode());
		result = prime * result + ((param3 == null) ? 0 : param3.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		TestParamEntity other = (TestParamEntity) obj;
		if (param1 == null) {
			if (other.param1 != null)
				return false;
		} else if (!param1.equals(other.param1))
			return false;
		if (param2 == null) {
			if (other.param2 != null)
				return false;
		} else if (!param2.equals(other.param2))
			return false;
		if (param3 == null) {
			if (other.param3 != null)
				return false;
		} else if (!param3.equals(other.param3))
			return false;
		return true;
	}
	@Override
	public String toString() {
		return "TestParamEntity [param1=" + param1 + ", param2=" + param2 + ", param3=" + param3 + "]";
	}
}

Receiver controller class

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RequestParamController {
	
	@PostMapping("/test/param")
	@CrossOrigin
	public TestParamEntity paramTest(TestParamEntity testParamEntity) {
		return testParamEntity;
	}
	
}

Note: the controller returns a java object (key value pair), so the datatype in the sender's ajax should also be changed to the corresponding key value pair type (that is, json)

Sender:

<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<title>parameter</title>
</head>
<body>

<!-- <a href="http://192.168.8.175:8087 / test / param? P = 111 & P2 = 222 "> a label connection < / a > -- >
<p>========================</p>
<input type="submit" onclick="ajaxsubmit()" value = "ajax Submit"/>

<script type="text/javascript">
	
	function ajaxsubmit () {
		var jsond = {
				param1 : 'a100',
				param2 : 'b200',
				param3 : 'c300'
			}
		
		$.ajax({
			url:"http://192.168.8.175:8087/test/param",
			type:"post",
// 			Data: json. Stringify (json), / / convert the json object into a json string, and the parameters passed are json strings
			data:jsond, // The parameters passed are json objects
			dataType:"json",
// 			contentType : "application/json;charset=UTF-8",
			success:function(result) {	
				// doSomething
				console.log(result);
			}
		});
	}
	
</script>
</body>
</html>

Test:

@Parameters of RequestBody annotation

@The explanation and principle of RequestBody is well written: https://blog.csdn.net/justry_deng/article/details/80972817/?ivk_sa=1024320u

Which scenarios can use @ RequestBody

Applicable scenario: Send a lump of data directly, not in key value pair format.

For example, now you want to send the string "lalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalala

Scenario 1: sending a request using ajax

<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<title>parameter</title>
</head>
<body>

<!-- <a href="http://192.168.8.175:8087 / test / param? P = 111 & P2 = 222 "> a label connection < / a > -- >
<p>========================</p>
<input type="submit" onclick="ajaxsubmit()" value = "ajax Submit"/>

<script type="text/javascript">
	
	function ajaxsubmit () {
		var jsond = {
				param1 : 'a100',
				param2 : 'b200',
				param3 : 'c300'
			}

		$.ajax({
			url:"http://192.168.8.175:8087/test/param",
			type:"post",
// 			Data: json. Stringify (json), / / convert the json object into a json string, and the parameters passed are json strings
			data:"lallalalalaa La la la la la la", // It's just a bunch of strings
// 			Data: json, / / the parameters passed are json objects
			dataType:"text",
// 			contentType : "application/json;charset=UTF-8",
			contentType : "application/text;charset=UTF-8",
			success:function(result) {	
				// doSomething
				console.log(result);
			}
		});
	}
	
</script>
</body>
</html>


be careful:

Receiver:

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RequestParamController {
	
	@PostMapping("/test/param")
	@CrossOrigin
	public String paramTest(@RequestBody String p) {
		return p;
	}
	
}

be careful:

Continue with the description above:

Test:

-Scenario 1.1 (one of scenario 1)

Change the data "lalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalala.

Sender:

<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<title>parameter</title>
</head>
<body>

<!-- <a href="http://192.168.8.175:8087 / test / param? P = 111 & P2 = 222 "> a label connection < / a > -- >
<p>========================</p>
<input type="submit" onclick="ajaxsubmit()" value = "ajax Submit"/>

<script type="text/javascript">
	
	function ajaxsubmit () {
		var jsond = {
				param1 : 'a100a',
				param2 : 'b200b',
				param3 : 'c300c'
			}

		$.ajax({
			url:"http://192.168.8.175:8087/test/param",
			type:"post",
			data:JSON.stringify(jsond), // Convert the json object into a json string, and the parameters passed are json strings
// 			Data: "lalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalala
// 			Data: json, / / the parameters passed are json objects
			dataType:"text",
			contentType : "application/json;charset=UTF-8",
// 			contentType : "application/text;charset=UTF-8",
			success:function(result) {	
				// doSomething
				console.log(result);
			}
		});
	}
	
</script>
</body>
</html>


be careful:

Receiver unchanged:

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RequestParamController {
	
	@PostMapping("/test/param")
	@CrossOrigin
	public String paramTest(@RequestBody String p) {
		return p;
	}
	
}

Test:

-Scenario 1.2: the sender sends a string in json format, and the receiver uses java objects to receive and encapsulate data.

Sender:

<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<title>parameter</title>
</head>
<body>

<!-- <a href="http://192.168.8.175:8087 / test / param? P = 111 & P2 = 222 "> a label connection < / a > -- >
<p>========================</p>
<input type="submit" onclick="ajaxsubmit()" value = "ajax Submit"/>

<script type="text/javascript">
   
   function ajaxsubmit () {
   	var jsond = {
   			param1 : 'a100aaa',
   			param2 : 'b200bbb',
   			param3 : 'c300ccc'
   		}

   	$.ajax({
   		url:"http://192.168.8.175:8087/test/param",
   		type:"post",
   		data:JSON.stringify(jsond), // Convert the json object into a json string, and the parameters passed are json strings
// 			Data: "lalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalalala
// 			Data: json, / / the parameters passed are json objects
   		dataType:"text",
   		contentType : "application/json;charset=UTF-8",
// 			contentType : "application/text;charset=UTF-8",
   		success:function(result) {	
   			// doSomething
   			console.log(result);
   		}
   	});
   }
   
</script>
</body>
</html>

Receiver:

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RequestParamController {
	
	@PostMapping("/test/param")
	@CrossOrigin
	public TestParamEntity paramTest(@RequestBody TestParamEntity testParamEntity) {
		return testParamEntity;
	}
	
}

be careful:


Test:


Change the dataType of the sender to json:

Test:

Scenario 2: send request using httpClient

Create a new interface to trigger httpclient requests

java

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import com.alibaba.fastjson.JSON;

@RestController
public class HttpClientController {
   
   
   @Autowired
   private RestTemplate template;

   @PostMapping("/http/client/test")
   public String httpClientTest() {
   	//Set request header
   	 HttpHeaders httpHeaders = new HttpHeaders();
   	 httpHeaders.add("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE); // Set the type of contentType to application/json
   	//Set request body
   	 Map<String, Object> params = new HashMap<>();
   	 params.put("param1", 1);
   	 params.put("param2", 2);
   	 params.put("param3", 3);
   	 
   	 String jsonData = JSON.toJSONString(params);  // A request parameter!! (string type!!)
   	 
   	 System.out.println("..................Requested parameters jsonData="+jsonData);
   	
   	 HttpEntity<String> request = new HttpEntity<>(jsonData, httpHeaders); // The request header (contentType) and the request body (a piece of data)
   	 
   	 String httpUrl = "http://localhost:8087/test/param"; //  Requested url
   	
   	 UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(httpUrl);
   	 
   	 TestParamEntity testParamEntity = template.postForObject(builder.toUriString(), request, TestParamEntity.class); // Send request
   	 
   	 System.out.println("..................Returned data testParamEntity="+testParamEntity);
   	 
   	 return "Test successful!!";
   	 
   }
   
   
}

The principle is the same as that of ajax sending requests, but it is implemented in java code


Test:

Execution results:

Scenario 3: quick test using postman


Receiver:

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RequestParamController {
	
	@PostMapping("/test/param")
	@CrossOrigin
	public TestParamEntity paramTest(@RequestBody TestParamEntity testParamEntity) {
		return testParamEntity;
	}
	
}

Text is selected as the format and JSON is not selected

If Text is selected, the content type in Headers is text/plain

At this time, if the receiver still uses java objects to receive, an error will be reported:

Test:

terms of settlement:
1. Or change the receiver's parameter type TestParamEntity to Stirng
perhaps
2. Change the content type in headers to application/json

Scenario 4: send requests in other forms as long as the rules are met

@The RequestParam annotation is mixed with the @ RequestBody annotation

Note: @ RequestBody can only have one interface at most, while @ ReqeustParam can have multiple

Test with postman

Receiver:

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RequestParamController {
	
	@PostMapping("/test/param")
	@CrossOrigin
	public String paramTest(@RequestBody TestParamEntity testParamEntity, String param4,String param5) {
		return testParamEntity + param4 + param5;
	}
	
}

Sender:


Test:

Good articles written online: https://blog.csdn.net/f123147/article/details/114832871

Tags: Spring Spring Boot

Posted on Fri, 26 Nov 2021 10:25:51 -0500 by Patch^