SpringMVC 获取请求数据的注解 @RequestBody与实体类RequestEntity 的基本用法

2023-07-08 08:08:32

在 Servlet 中有格HttpServletRequest 的方法可以使使我们可以轻松获取请求数据, 包括请求头、请求体。而在 SpringMVC 中一方面可以利用 Servlet 的 API 来获取请求数据;另一方面也提供了注解和实体类的方式来更加方便的获取。话不多说,直接上代码。
其中,前端代码为 themleaf 引擎构造出来,分别构造出两个输入用户数据的文本框,在后端进行分别测试 @RequestBody 与RequestEntity

<!DOCTYPEhtml><htmllang="en"xmlns:th="http://www.themleaf.org"><head><metacharset="UTF-8"><title>Title</title></head><body><formth:action="@{/testHttpRequestBody}"method="post">
    用户名:<inputtype="text"name="username"><br>
    密码:<inputtype="password"name="password"><br>
    爱好:<inputtype="checkbox"name="hobby"value="a">a<inputtype="checkbox"name="hobby"value="b">b<inputtype="checkbox"name="hobby"value="c">c<br><inputtype="submit"value="登录"></form><formth:action="@{/testHttpRequestEntity}"method="post">
    用户名:<inputtype="text"name="username"><br>
    密码:<inputtype="password"name="password"><br>
    爱好:<inputtype="checkbox"name="hobby"value="a">a<inputtype="checkbox"name="hobby"value="b">b<inputtype="checkbox"name="hobby"value="c">c<br><inputtype="submit"value="登录"></form></body></html>

后端代码

packagecom.wpp.controller;importorg.springframework.http.RequestEntity;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.RequestBody;importorg.springframework.web.bind.annotation.RequestMapping;@Controller@RequestMapping(value="/")publicclassHttpController{@RequestMapping(value="testHttpRequestBody")publicStringtestHttpRequestBody(@RequestBodyString request){System.out.println(request);return"success";}@RequestMapping(value="testHttpRequestEntity")publicStringtestHttpRequestBody(RequestEntity<String> requestEntity){System.out.println("body:"+requestEntity.getBody());System.out.println("header:"+requestEntity.getHeaders());System.out.println("url:"+requestEntity.getUrl());return"success";}}

分别展示请求数据
展示 RequestBody 为

username=admin&password=123456&hobby=a&hobby=b&hobby=c

展示 RequestEntity 实体类为

body:username=admin&password=123456&hobby=a&hobby=b&hobby=c
header:[host:"localhost:8080", connection:"keep-alive", content-length:"54", cache-control:"max-age=0", upgrade-insecure-(。。。。省略)
url:http://localhost:8080/SpringMVC/testHttpRequestEntity

会发现 RequestBody 仅仅是对于请求体的数据。 RequestEntity 更为全面 url、请求体、请求体、请求方法等都能获得。
对于使用方法上,@RequestBody 是注解的方式,RequestEntity 则是一个实体类。

  • 作者:培鹏
  • 原文链接:https://blog.csdn.net/Artisan_w/article/details/121388995
    更新时间:2023-07-08 08:08:32