package com.zyp.controller.test;
import com.zyp.common.NoLogin;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
/**
* @author syl
* @description 面试复习
* @since 2022/6/29
*/
@RestController
@RequestMapping("test11/")
@Api(tags = "面试复习")
public class TestController1 {
@ApiOperation("测试requestParam")
@GetMapping("requestParam")
@NoLogin
public String testRequestParam(@RequestParam String id){
return id;
}
@NoLogin
@ApiOperation("测试requestParam")
@GetMapping("PathVariable/{id}")
public String testPathVariable(@PathVariable String id){
return id;
}
}
输入url:http://localhost:9002/test11/requestParam
结果:报400错,默认参数id是必传的,若使用此注解时要求id不是必传的,则要求给注解的defaultValue()属性赋值,比如@RequestParam(defaultValue = “1”)
输入url:http://localhost:9002/test11/requestParam?id=1
结果:返回1
输入url:http://localhost:9002/test11/PathVariable/
结果:报400错,默认参数id是必传的,若使用此注解时要求id不是必传,则@PathVariable(required = false),此时参数值可以为null
输入url:http://localhost:9002/test11/PathVariable/1
结果:返回1
package com.zyp.controller.test;
import com.zyp.common.NoLogin;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
/**
* @author syl
* @description 面试复习
* @since 2022/6/29
*/
@RestController
@RequestMapping("test11/")
@Api(tags = "面试复习")
public class TestController1 {
@ApiOperation("测试requestParam")
@GetMapping("requestParam")
@NoLogin
public String testRequestParam(@RequestParam(value = "id1") String id){
return id;
}
/**
* PathVariable/{id1}的id1必须和@PathVariable(value = "id1")的value的一致方可取出相应的值
* @param id
* @return
*/
@NoLogin
@ApiOperation("测试requestParam")
@GetMapping("PathVariable/{id1}")
public String testPathVariable(@PathVariable(value = "id1") String id){
return id;
}
}
输入url:http://localhost:9002/test11/requestParam?id=1
结果:报400错,@RequestParam(value = “id1”)表示从路径或者请求体中参数id1,如果没有参数id1则报错
注:@RequestParam(name = “id1”)同上
输入url:http://localhost:9002/test11/requestParam?id1=1
结果:返回1
总结:PathVariable一般用于get请求,取出路径中的参数
RequestParam可以用于所有请求,取出对应的参数值
RequestBody:用于接收请求体的参数,不能用于get请求中