@PathVariable注解

spring通过@PathVariable注解来获得请求url中的动态参数的,并且支持动态url访问,可以从url中直接提取参数而不需要采用?q=q&d=d的形式

代码示例如下:


@RestController
@RequestMapping("/dynamic")
public class DynamicUrlController {
//localhost:8080/dynamic/id/123:hello
@RequestMapping("/id/{id}")
public String id(
@PathVariable("id") String id ) {
return id;
}
//localhost:8080/dynamic/number/123:hello
@RequestMapping("/number/{number}:hello")
public int number(
@PathVariable("number") int number ) {
return number;
}
//localhost:8080/dynamic/number/123:hello/t
@RequestMapping("/number/{number}:hello/t")
public int anInt(
@PathVariable("number") int number ) {
return number;
}
//localhost:8080/dynamic/number/qwerwww333/t
@RequestMapping("/number/{number:[a-z-]+}{other:\d{3}}/t")
public String regular(
@PathVariable("number") String number ,
@PathVariable("other")String other) {
return number+other;
}
//不支持
/* @RequestMapping("/date/{date}")
public Date date(
@PathVariable("date") Date date ) {
return date;
}*/
}

同时变量url中的PathVariable还支持正则表达式校验,上面最后一个方法只能字母加后缀三个数字的方式访问

原文地址:https://www.cnblogs.com/heapStark/p/8214131.html