@RequestParam vs @PathVariable

前端 未结 7 990
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 06:22

What is the difference between @RequestParam and @PathVariable while handling special characters?

+ was accepted by @Re

7条回答
  •  一个人的身影
    2020-11-22 06:27

    1) @RequestParam is used to extract query parameters

    http://localhost:3000/api/group/test?id=4
    
    @GetMapping("/group/test")
    public ResponseEntity test(@RequestParam Long id) {
        System.out.println("This is test");
        return ResponseEntity.ok().body(id);
    }
    

    while @PathVariable is used to extract data right from the URI:

    http://localhost:3000/api/group/test/4
    
    @GetMapping("/group/test/{id}")
    public ResponseEntity test(@PathVariable Long id) {
        System.out.println("This is test");
        return ResponseEntity.ok().body(id);
    }
    

    2) @RequestParam is more useful on a traditional web application where data is mostly passed in the query parameters while @PathVariable is more suitable for RESTful web services where URL contains values.

    3) @RequestParam annotation can specify default values if a query parameter is not present or empty by using a defaultValue attribute, provided the required attribute is false:

    @RestController
    @RequestMapping("/home")
    public class IndexController {
    
        @RequestMapping(value = "/name")
        String getName(@RequestParam(value = "person", defaultValue = "John") String personName) {
            return "Required element of request param";
        }
    
    }
    

提交回复
热议问题