在Spring MVC中,我们可以通过将实体类型作为控制器方法的参数来获取请求参数。Spring MVC会自动将请求中的参数映射到实体类的属性中。
代码如下:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class UserController {
@PostMapping("/user")
@ResponseBody
public String createUser(@RequestBody User user) {
return "Created user: " + user.toString();
}
}
在上面代码中,定义了一个 User 实体类,包含了用户的属性。在 createUser 方法中,使用 @RequestBody 注解将 User 对象作为参数,Spring MVC会自动将请求体中的JSON数据映射到 User 对象中。
public class User {
private String name;
private int age;
}
通过这种方式,可以直接将请求体中的JSON数据映射到实体类中,避免了手动解析请求参数的繁琐过程。
原文链接: https://blog.csdn.net/2401_82884096/article/details/137960959