提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
在 Java Web 开发中,Controller 是应用程序的入口点,负责处理请求并返回响应结果。实际开发中,Controller 通常需要接收客户端传递过来的参数,并将这些参数传递给 Service 层进行业务处理。在传递查询参数时,我们可以使用 Query 和 Param 参数来传递参数值。
一、query参数
Query 参数通常在 GET 请求中使用,它以查询字符串(Query String)的形式出现在 URL 中,例如:
http://localhost:8080/user?name=Alice&age=20 |
其中,name 和 age 都是查询参数,它们的值分别为 Alice 和 20。在 Controller 中获取查询参数通常有两种方式:
1)使用 @RequestParam 注解
@GetMapping("/user") public List<User> getUser(@RequestParam("name") String name, @RequestParam("age") int age) { return userService.findUsersByNameAndAge(name, age); } |
这里,@RequestParam 注解用来绑定方法参数与请求参数,其 value 属性指定了查询参数名,method 属性可指定 HTTP 请求方法,defaultValue 属性可设置默认值。
2)使用 HttpServletRequest 对象
@GetMapping("/user") public List<User> getUser(HttpServletRequest request) { String name = request.getParameter("name"); int age = Integer.parseInt(request.getParameter("age")); return userService.findUsersByNameAndAge(name, age); } |
这里,通过 HttpServletRequest 对象获取查询参数的值,然后传递给 Service 层进行业务处理。
二、param参数
Param 参数通常在 POST、PUT 或 DELETE 请求中使用,它以请求体的形式传递参数值。在 Controller 中获取 Param 参数值通常有两种方式:
1.使用@RequestBody注解
代码如下(示例):
@PostMapping("/user")
public User addUser(@RequestBody User user) {
return userService.addUser(user);
}
这里,@RequestBody 注解用来将 JSON 请求体反序列化为 Java 对象,然后传递给 Service 层进行业务处理。
2.使用@RequestParam 注解
代码如下(示例):
@PostMapping("/user")
public User addUser(@RequestParam("name") String name,
@RequestParam("age") int age,
@RequestParam("email") String email) {
User user = new User(name, age, email);
return userService.addUser(user);
}
这里,@RequestParam 注解用来绑定方法参数与请求参数,其 value 属性指定了 Param 参数名。
总结
总的来说,Query 和 Param 参数的使用场景和传递方式都有所不同,在实际开发中需要根据实际需求来选择使用哪种方式来传递参数值。