目录
一、常用注解区别
@RequestParam
、@RequestBody
、@Param
和@PathVariable
这四个注解在Spring框架中各自具有不同的用途和区别。
- @RequestParam:
- 主要用于接收URL中的查询参数或表单数据中的字段。
- 通常用于GET请求,但也可以用于POST请求。
- 在方法参数上添加该注解,可以指定参数名称和是否必需。
- 示例:
@RequestParam("name") String name
。
- @RequestBody:
- 主要用于处理HTTP请求体中的数据,通常用于POST、PUT等请求方法。
- 该注解通常与
@PostMapping
、@PutMapping
等注解一起使用。 - 请求体中的数据通常是以JSON、XML等格式发送的,
@RequestBody
可以将请求体中的数据自动绑定到指定的Java对象上。 - 示例:
@RequestBody User user
,其中User
是一个自定义的Java类。
- @Param:
- 主要用于命名URI模板变量,使得在控制器方法中可以引用这些变量。
- 该注解通常与
@RequestMapping
或@GetMapping
等注解一起使用。 - 通过
@Param
注解可以为URI模板变量提供名称,然后在方法参数中使用该名称来接收变量的值。 - 示例:
@GetMapping("/users/{userId}")
public String showUser(@Param("userId") Long id)
。
- @PathVariable:
- 主要用于接收URI模板变量的值。
- 该注解通常与
@RequestMapping
或@GetMapping
等注解一起使用,用于提取URI中的变量部分。 - 示例:对于URI
/users/{userId}
,可以使用@PathVariable Long userId
来提取{userId}
的值。
总结:
@RequestParam
和@PathVariable
都是用于从请求中提取参数的,但@RequestParam
用于提取查询参数,而@PathVariable
用于提取URI模板变量。@RequestBody
用于处理请求体中的数据,通常与POST、PUT等请求方法一起使用。@Param
主要用于命名URI模板变量,使得在方法参数中可以引用这些变量。
二、@RequestParam
示例
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple Form Example</title>
</head>
<body>
<h2>Please Fill Out the Form</h2>
<form action="/submitForm" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>
<label for="age">Age:</label>
<input type="number" id="age" name="age" required><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
controller:
package com.example.demo.controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class FormController {
@PostMapping("/submitForm")
public String handleFormSubmission(@RequestParam String name, @RequestParam int age) {
// 处理表单数据
// 这里只是简单地将接收到的数据返回给客户端
return "Name: " + name + ", Age: " + age;
}
}
三、@RequestBody
示例
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Submit Form with Axios</title>
<!-- 引入axios -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<!-- 表单 -->
<form id="submit-form">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<label for="age">Age:</label>
<input type="number" id="age" name="age">
<button type="submit">Submit</button>
</form>
<!-- JavaScript代码 -->
<script>
// 获取表单元素
const form = document.getElementById('submit-form');
// 为表单添加提交事件监听器
form.addEventListener('submit', function(event) {
// 阻止表单的默认提交行为
event.preventDefault();
// 获取表单数据
const name = document.getElementById('name').value;
const age = document.getElementById('age').value;
// 创建要发送的数据对象
const data = {
name: name,
age: age
};
// 使用axios发送POST请求
axios.post('/api/submit', data)
.then(response => {
// 请求成功处理
console.log(response.data); // 打印后端返回的响应数据
// 可以在这里更新页面或显示消息给用户
})
.catch(error => {
// 请求失败处理
console.error('Error:', error);
// 可以在这里显示错误消息给用户
});
});
</script>
</body>
</html>
controller:
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@PostMapping("/api/submit")
public String handleSubmit(@RequestBody MyData data) {
// 处理data对象
String name = data.getName();
int age = data.getAge();
// 返回响应
return "Data received: " + name + ", " + age;
}
}
四、@Param
示例
@RestController
public class UserController {
@GetMapping("/users/{userId}")
public String getUser(@Param("userId") Long id) {
// 你可以直接使用id参数来查询用户信息
return "User with ID: " + id + " was retrieved";
}
}
五、@PathVariable示例
@RestController
public class UserController {
@GetMapping("/users/{userId}")
public String getUser(@PathVariable Long userId) {
// 你可以直接使用userId参数来查询用户信息
return "User with ID: " + userId + " was retrieved";
}
}