在Spring Boot中,可以通过以下方式接收各种类型的参数:
- 通过HTTP请求参数(如查询字符串,表单数据等):
@RestController
public class MyController {
@GetMapping("/greet")
public String greet(@RequestParam(name = "name", defaultValue = "World") String name) {
return "Hello, " + name + "!";
}
}
- 通过路径变量:
@RestController
public class MyController {
@GetMapping("/greet/{name}")
public String greetWithPath(@PathVariable("name") String name) {
return "Hello, " + name + "!";
}
}
- 通过HTTP头部信息:
@RestController
public class MyController {
@GetMapping("/greet")
public String greetWithHeader(@RequestHeader("Name") String name) {
return "Hello, " + name + "!";
}
}
- 通过Cookie:
@RestController
public class MyController {
@GetMapping("/greet")
public String greetWithCookie(@CookieValue("name") String name) {
return "Hello, " + name + "!";
}
}
- 通过请求体中的JSON数据:
@RestController
public class MyController {
@PostMapping("/greet")
public Greeting greetWithJson(@RequestBody Greeting greeting) {
return greeting;
}
}
public class Greeting {
private String name;
// Getters and setters
}
- 通过会话属性(通过
HttpSession
):
@RestController
public class MyController {
@GetMapping("/greet")
public String greetWithSession(HttpSession session) {
String name = (String) session.getAttribute("name");
return "Hello, " + name + "!";
}
}
- 通过Servlet API(如
HttpServletRequest
):
@RestController
public class MyController {
@GetMapping("/greet")
public String greetWithServletApi(HttpServletRequest request) {
return "Hello, " + request.getParameter("name") + "!";
}
}
以上是Spring Boot中接收参数的一些常见方式,可以根据实际需求选择合适的方法。