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注解

原文地址:https://www.cnblogs.com/junzifeng/p/11947270.html