SpringBoot筆記 -- @RequestParam、@RequestBody、@PathVariable、@param


前言

在SpringBoot開發項目中,傳參經常用到這幾個注解,在這里總結記錄一下他們的使用及區別。

@PathVariable

通過 @PathVariable 可以將 URL 中占位符參數綁定到控制器處理方法的入參中:URL 中的 {xxx} 占位符可以通過@PathVariable("xxx") 綁定到操作方法的入參中。

    @GetMapping("/{modelId}")
    @ApiOperation("根據設備型號ID獲取設備型號詳細信息")
	public ResponseEntity<DeviceModel> findDeviceModel(@PathVariable("modelId") String modelId) {
		return ResponseEntity.ok(deviceModelService.findById(modelId));
	}

上面這個接口可通過get請求 http://xxxxx/1111來得到想要的數據,1111既是findDeviceModel的方法參數又是@RequestMapping的路由。如果方法參數不想寫成和路由一樣的應該怎么辦?看代碼:

    @GetMapping("/{deviceModelId}")
    @ApiOperation("根據設備型號ID獲取設備型號詳細信息")
	public ResponseEntity<DeviceModel> findDeviceModel(@PathVariable("deviceModelId") String modelId) {
		return ResponseEntity.ok(deviceModelService.findById(modelId));
	} 

@RequestParam

@RequestParam和@PathVariable的區別就在於請求時當前參數是在url路由上還是在請求的body上,例如有下面一段代碼:

    @GetMapping("/list")
    @ApiOperation("查詢設備型號列表")
    public ResponseEntity findDeviceModelList(DeviceModel deviceModel, @RequestParam(value="pageSize", required=true, defaultValue="10") Integer pageSize, @RequestParam(value="pageNum", required=true, defaultValue="1") Integer pageNum) {
		return ResponseEntity.ok(deviceModelService.query(deviceModel, pageSize, pageNum));
	}

這個接口的請求url這樣寫:http://xxxxx?phoneNum=xxxxxx,也就是說被@RequestParam修飾的參數最后通過key=value的形式放在http請求的Body傳過來,對比下上面的@PathVariable就很容易看出兩者的區別了。

@RequestBody

@RequestBody能把簡單json結構參數轉換成實體類,如下代碼:

        @PostMapping("/add")
	@ApiOperation("新增設備型號")
	public ResponseEntity<?> create(@RequestBody DeviceModel deviceModel) {
		if(deviceModelService.isExistDeviceModelName(deviceModel)){
			throw new IndustryException("設備型號名稱重復");
		}
		return ResponseEntity.ok(deviceModelService.create(deviceModel));
	}        

@Param

Mybatis 的 @Param注解


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM