参数重命名
利用注解@RequestParam为参数重命名
举个栗子🌰
有两个参数 String t1(起始时间), String t2(结束时间)
滑稽老哥觉得 t1, t2 这两个名字不太好, 想要改成 startTime, endTime
于是利用注解@RequestParam为参数重命名
将 t1 重命名为 startTime
将 t2 重命名为 endTime
@GetMapping("time") public String showTime( @RequestParam(value = "t1", required = false) String startTime, @RequestParam(value = "t2", required = false) String endTime) { return "开始时间: " + startTime + " | 结束时间: " + endTime; }
对于 required 的解释🍭
分析@RequestParam()源码发现, required默认为 true
即忘记填写对应的 key 时就会报错
设置required为 false
传递对象
当所需获取的参数较多时, 可通过传递对象的方式进行传参
设置对象属性🍂
@Data public class User { private int id; private String name; private int age; }
传递对象🍂
@RestController @RequestMapping("/test") public class TestController { // 传递对象 @GetMapping("/user") public String showUser(User user) { return user.toString(); } }
注意🍭
URL 中的 key 必须与所传对象的属性一致
错误示范🍭
传递 JSON 对象
利用注解@RequestBody传递 JSON 对象
@RestController @RequestMapping("/test") public class TestController { // 传递 JSON 对象 @PostMapping("/json-user") // 推荐使用 @PostMapping public String showJsonUser(@RequestBody(required = false) User user) { return user.toString(); } }
注意🍭
此处不建议使用@GetMapping传递 JSON 对象 , @GetMapping默认使用 URL 传递参数
获取 URL 中的参数
http://127.0.0.1:8080/test/login?username=bibubibu
http://127.0.0.1:8080/test/login/bibubibu
此处所指获取 URL 中的参数是后者的形式
即/后面就是参数, 而不是?username=bibubibu
利用注解@PathVariable获取 URL 中的参数
举个栗子🌰
需要传递的参数用 { } 包裹
{username}
{password}
@RestController @RequestMapping("/test") public class TestController { @RequestMapping("/login/{username}/{password}") public String login( @PathVariable(value = "username", required = false) String username, @PathVariable(value = "password", required = false) String password) { return "username: " + username + " | password: " + password; } }
上传文件
利用注解@RequestPart上传文件
@RestController @RequestMapping("/test") public class TestController { // 上传文件 @RequestMapping("/upfile") public String upFile(@RequestPart("files") MultipartFile file) throws IOException { // 1. 根目录 String path = "D:\\Java\\documents\\png_file\\"; // 2. 根目录 + 唯一文件名 path += UUID.randomUUID().toString().replace("-", ""); // 3. 根目录 + 唯一文件名 + 文件后缀 path += file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); // 4. 保存文件 file.transferTo(new File(path)); return path; } }
获取 Cookie / header / Session
Spring MVC 内置了 HttpServletRequest, HttpServletResponse
传统方式获取 Cookie
传统方式获取 Cookie—通过 Servlet 获取(获取全部 Cookie)
@RestController @RequestMapping("/test") @Slf4j public class TestController { @RequestMapping("/getCookies") public String getCookies(HttpServletRequest req) { Cookie[] cookies = req.getCookies(); for(Cookie item : cookies) { log.error(item.getName() + " | " + item.getValue()); } return "getCookies~~"; } }
校验🍭
添加 Cookie
运行查看结果











