在Spring Servlet中接收JSON POST参数作为@RequestParam,可以通过以下步骤实现:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.10</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.5</version>
</dependency>
@RequestBody
注解将JSON参数绑定到一个Java对象上。同时,使用@RequestMapping
注解指定请求的URL和HTTP方法。import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/example")
public class ExampleController {
@PostMapping("/json")
public String handleJsonRequest(@RequestBody MyJsonData jsonData) {
// 处理接收到的JSON数据
return "Received JSON data: " + jsonData.toString();
}
}
public class MyJsonData {
private String name;
private int age;
// 省略构造函数、getter和setter方法
@Override
public String toString() {
return "Name: " + name + ", Age: " + age;
}
}
Content-Type: application/json
。使用Postman等工具发送POST请求,请求URL为http://localhost:8080/example/json
,请求体为以下JSON数据:
{
"name": "John",
"age": 25
}
MyJsonData
对象,并将其作为参数传递给handleJsonRequest
方法。你可以在方法中对接收到的JSON数据进行处理。这样,你就可以在Spring Servlet中接收JSON POST参数作为@RequestParam了。
关于Spring MVC和JSON数据的更多信息,你可以参考腾讯云的相关产品文档:
领取专属 10元无门槛券
手把手带您无忧上云