@RequestParam
获取一个请求中的参数,例如:一个请求url为http://localhost:8080/student?id=123456&name=张三&age=22
url中‘?’前为请求地址,‘?’后为地址携带的参数,多个参数用&连接
@RestController
public class TestController {
@GetMapping("student")
public void student(@RequestParam String id,
@RequestParam("name") String name,
@RequestParam("age") Integer age){
System.out.println("通过@RequestParam接收到的id为:"+id);
System.out.println("通过@RequestParam接收到的name为:"+name);
System.out.println("通过@RequestParam接收到的age为:"+age);
}
}
调用结果为:
可以看到@RequestParam将url中的参数值赋值给了注解后面定义的参数中,并且匹配方式是根据命名来匹配的,也可以通过自定义@RequestParam("url中参数名")来获取url中某一参数的值。
@PathVariable
通常用于Restful风格的url,例如
http://localhost:8080/student/123/张三/23
可以看到这种风格的url没有‘?’来传递参数,而是直接将要传递的参数的值放在了地址中;
@RestController
public class TestController {
@GetMapping("student/{id}/{name}/{age}")
public void student2(@PathVariable String id,
@PathVariable("name") String name,
@PathVariable("age") Integer age){
System.out.println("通过@PathVariable接收到的id为:"+id);
System.out.println("通过@PathVariable接收到的name为:"+name);
System.out.println("通过@PathVariable接收到的age为:"+age);
}
}
接口调用结果为:
在@GetMapping中使用{}来做占位符 ,将url中占位符的值赋值给了注解后面定义的参数中,并且
匹配方式也是通过命名来匹配的,并且也可以通过自定义@PathVariable("自定义的值")来获取到对应的值
@RequestBody
获取一个请求中请求体中的内容;例如:
该请求的请求体是一个JSON,接口
@RestController
public class TestController {
@PostMapping("/student")
public void student(@RequestBody String student){
System.out.println(student);
}
}
接口调用结果为:
可以看到被@RequestBody修饰的student参数的值就是这个请求中请求体的JSON值;
@RequestBody还可以将这个JSON转换成想要的对象,例如:
这是一个自定义的实体类:
这是请求,请求体中的JSON就是实体类的JSON形式
@RestController
public class TestController {
@PostMapping("/student")
public void student(@RequestBody Student student){
System.out.println(student);
System.out.println(student.getId());
System.out.println(student.getName());
System.out.println(student.getAge());
}
}
@RequestBody修饰的参数由String换成Student对象
接口调用结果:
可以看到请求中请求体的JSON转换成了参数Student对象 ,同理还可以将请求体中的数据转成其他想要的对象