SpringMVC 获取请求参数的几种方式
-
**@PathVariable: **
@GetMapping("/test/{id}") public String testPath1(@PathVariable("id") int id){ return "testPath1"; }
Note: 当有精确匹配,springmvc会选择精确匹配的那个controller方法
-
通过原生servlet来获取(用的比较少)
@GetMapping("/testServletApi") public String testServletApi(HttpServletRequest request){ String username = request.getParameter("username"); String password = request.getParameter("password"); return "testServletApi"; }
-
通过形参直接获取值
@GetMapping("/testParam") // 形参名字和请求参数名字相同时可以不写注解 public String testParam(String username, String password) { return "testServletApi"; }
Note: 当请求参数中有多个同名的请求参数时(如: name=1&name=2)
a. 当使用String name 得到的是用逗号隔开
b. 当时有 String[] name 得到的就是字符串数组 -
通过形参直接获取值,请求参数和形参名字不同 @RequestParam(“user_name”)
@GetMapping("/testParam") public String testParam( @RequestParam("user_name") String username, @RequestParam("pass_word") String password) { return "testServletApi"; }
@RequestParam(value = "user_name",required = false,defaultValue = "admin") String username,
当required=false 如果请求参数中没有user_name也不会报错
defaultValue: 默认值; -
获取Header中数据 @RequestHeader
@GetMapping("/testHeader") public String testHeader( @RequestHeader("Host") String host) { return "testHeader"; }
-
获取Cookie中数据 @CookieValue
@GetMapping("/testCookie") public String testCookie( @CookieValue("JSESSIONID") String sessionId) { return "testCookie"; }
-
使用实体类来接收请求参数
@GetMapping("/testPOJO") public String testPOJO(User user) { return "testPOJO"; } // 这样会将请求数据注入到实体类中的对应属性 // 且只要形参满足请求参数都会被注入进去,意味着会重复注入
-
获得请求体@RequestBody
@GetMapping("/testRequestBody") public String testPOJO(@RequestBody String requestBody) { System.out.println(requestBody); return "testRequestBody"; } // requestBody为body内容 { "username":"linxc", "password":"sdfsaf" }