@ModelAttribute、@RequestBody、@RequestParam、@PathVariable 注解对比
<p><span data-cke-copybin-start="1"></span>整理了下接收参数的注解。</p><table>
<thead>
<tr>
<th>注解</th>
<th>绑定来源</th>
<th>支持类型</th>
<th>典型用途</th>
<th>备注</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>@ModelAttribute</code></td>
<td>请求参数自动绑定到 JavaBean(含嵌套对象)</td>
<td>JavaBean(含集合)</td>
<td>表单提交(<code>application/x-www-form-urlencoded</code>)</td>
<td>可用于初始化默认值</td>
</tr>
<tr>
<td><code>@RequestBody</code></td>
<td>请求体(JSON/XML)</td>
<td>任意类型(常用于对象)</td>
<td>JSON 请求体 <code>{"id":1,"name":"Tom"}</code></td>
<td>常与 <code>@PostMapping</code>、<code>@PutMapping</code> 结合使用</td>
</tr>
<tr>
<td><code>@RequestParam</code></td>
<td>请求参数(Query 或 Form)</td>
<td>基本类型、String、数组、List</td>
<td><code>?id=1&name=Tom</code></td>
<td>适合简单参数</td>
</tr>
<tr>
<td><code>@PathVariable</code></td>
<td>URL 路径参数</td>
<td>基本类型、String</td>
<td><code>/user/123 → id=123</code></td>
<td>REST 风格接口</td>
</tr>
</tbody>
</table>
<p>简单示例对比</p>
<p><strong>@ModelAttribute</strong></p>
<pre class="language-java highlighter-hljs"><code>@PostMapping("/register")
public String register(@ModelAttribute User user) {
// 表单数据将自动绑定到 User 对象中
return "userInfo";
}</code></pre>
<p><strong>@RequestBody</strong></p>
<pre class="language-java highlighter-hljs"><code>@PostMapping("/api/user")
public ResponseEntity<?> saveUser(@RequestBody User user) {
// JSON 请求体 {"name":"Tom","age":20}
return ResponseEntity.ok(user);
}</code></pre>
<p><strong>@RequestParam</strong></p>
<pre class="language-java highlighter-hljs"><code>@GetMapping("/search")
public String search(@RequestParam String keyword) {
// /search?keyword=java
return keyword;
}</code></pre>
<p><strong>@PathVariable</strong></p>
<pre class="language-java highlighter-hljs"><code>@GetMapping("/user/{id}")
public String getUser(@PathVariable Long id) {
return "ID: " + id;
}</code></pre>
<p>注意,@RequestBody 需要使用 HttpMessageConverter(如 Jackson、FastJson)支持 JSON 解析。</p>
<p style="text-align: right"><span style="color: rgba(53, 152, 219, 1)">恐惧与否是你的选择。-- 烟沙九洲</span></p><br><br>
来源:https://www.cnblogs.com/yanshajiuzhou/p/18903319
頁:
[1]