SpringBoot中Controller接收参数的几种方式

    科技2022-08-15  106

    第一类:请求路径参数

    1、@PathVariable

    @GetMapping("getcitylist/{id}") public List<Classify> getCityList(@PathVariable("id") Long id) {

    获取路径参数。即url/{id}这种形式。

    2、@RequestParam

    @GetMapping("ceshi") public List<Long> getCityList(@RequestParam("name") String name) {

    获取查询参数。即url?name=这种形式

    第二类:Body参数 3、@RequestBody 传入Json时,请求方式不能用Get请求

    @PostMapping("/getCustomerList") public JsonObject getCustomerList(@RequestBody Customer customer){

    Customer为项目中的POJO类,用于接收对象

    也可以这样

    @PostMapping(path = "/demo1") public void demo1(@RequestBody Map<String, String> person) {

    使用Map接收时不需要POJO类

    第三类:请求头参数以及Cookie

    1、@RequestHeader 2、@CookieValue

    @GetMapping("/demo3") public void demo3(@RequestHeader(name = "myHeader") String myHeader, @CookieValue(name = "myCookie") String myCookie) { System.out.println("myHeader=" + myHeader); System.out.println("myCookie=" + myCookie); }

    也可以这样

    @GetMapping("/demo3") public void demo3(HttpServletRequest request) { System.out.println(request.getHeader("myHeader")); for (Cookie cookie : request.getCookies()) { if ("myCookie".equals(cookie.getName())) { System.out.println(cookie.getValue()); } } }
    Processed: 0.015, SQL: 9