getAllUsers(){return userRepository.findAll();} @PostMapping@PostMapping 就等价于@RequestMapping(value="http://kandian.youth.cn/users",method =RequsetM。SpringBoot常用注解( 二 )。" />

SpringBoot常用注解( 二 )


@GetMapping("/users")public ResponseEntity> getAllUsers(){return userRepository.findAll();}@PostMapping@PostMapping 就等价于@RequestMapping(value="http://kandian.youth.cn/users",method =RequsetMethod.POST)即使用@PostMapping就相当用接收Post方法了
@PostMapping("/users")public ResponseEntity> getAllUsers(){return userRepository.findAll();}@PutMapping@PutMapping("/users/{userId}")等价于@RequestMapping(value = http://kandian.youth.cn/index/“/users/{userId}”,method = RequestMethod.PUT)
@PutMapping("/users/{userId}")public ResponseEntity updateUser(@PathVariable (value ="http://kandian.youth.cn/index/userId")Long userId, @Valid @RequestBody UserUpdateRequest userUpdateRequest){...}@DeleteMapping@DeleteMapping("/users/{userId}")等价于@RequestMapping(value ="http://kandian.youth.cn/users/{userId}",method = RequestMethod.DELETE)
@DeleteMapping("/users/{userId}")public ResponseEntity deleteUser(@PathVariable(value = "http://kandian.youth.cn/index/userId) Long userId){...}那么我们如何进行Put/Delete方法的获取呢答案是通过隐藏域利用_method设定浏览器传给Controller的方法类型

前后端传值@ParhVariable和@RequestParam@PathVariable 用于获取路径参数 ,@RequestParam用于获取查询参数
@GetMapping("/users/{userId}/teachers")public List getUserRelatedTeachers(@PathVariable("userId") Long userId,@RequestParam(value = "http://kandian.youth.cn/index/type",required = false) String type){...}其中@PathVariable是获取请求中的{userId}值 , @RequestParam则是url读取请求中type的值比如我们url请求中/users/{123456}/teachers?type=Chinese则我们在Controller获取到的就是userId = 123456 , type = Chinese
另在@RequestParam中 value=http://kandian.youth.cn/index/“参数名” required = “true/false”(true表示参数不允许不存在 , false表示参数允许不存在) defaultValue="" 设置defaultValue时默认required为false 。
@RequestBody用于读取Request请求的body部分 , 且Content-Type为application/json格式数据 , 接收到数据后会自动将数据绑定在Java对象上 , 系统会使用HttpMessageConverter来讲请求的body中的json字符串转换为Java对象
@PostMapping("/sing-up")public ResponseEntity signUp(@RequsetBody @Valid UserRegisterRequest userRegisterRequest){userService.save(userRegisterRequest);return ResponseEntity.ok().build()'}