@RequestParam和@PathVariable的用法与区别

package com.cherish.controller;

import com.cherish.commonutils.ResultData;
import org.springframework.web.bind.annotation.*;

/**
 * pathVariable参数需要拼接到路径中,不需要判空
 * (@PathVariable String id,@PathVariable String name)
 *
 * 地址栏访问地址 :http://localhost:9090/get/pathVariable/520/cherish
 *
 * requestParam不要要拼接到路径中 @RequestParam("id") String id,@RequestParam("name"
 *  地址栏访问地址:  http://localhost:9090/get/requestParam?id=520&name=cherish
 *
 *  1、当URL指向的是某一具体业务资源(或资源列表),例如博客,用户时,使用@PathVariable
 *
 * 2、当URL需要对资源或者资源列表进行过滤,筛选时,用@RequestParam
 */
@RestController
@RequestMapping("/get")
public class TestRequestController {

    @GetMapping("/requestParam")
    public ResultData getParam(@RequestParam("id") String id,@RequestParam("name") String name){

        return ResultData.ok().data("id",id).data("name",name);
    }

    @GetMapping("pathVariable/{id}/{name}")
    public ResultData getPath(@PathVariable String id,@PathVariable String name){
        return ResultData.ok().data("id",id).data("name",name);
    }
}

posted @ 2021-04-30 17:59  Cherish°  阅读(150)  评论(0编辑  收藏  举报