只有当蔬菜名称不是胡萝卜、 bean 类或洋葱时,我才想访问该方法,因此如果我给番茄,它应该返回 View 。我使用的网址如下,此网址有什么问题吗?
@RequestMapping("/**/vegetables/{name:^[carrot|beans|onions]}")
public String vegetablesNames(){
return "vegetables";
}
最佳答案
您应该在方法内部进行验证:
@RequestMapping("/vegetables/{name}")
public String vegetablesNames(@PathVariable String name){
if (name.matches("your regex") {
throw new RuntimeException(name + " doesn't match");
}
return "vegetables";
}
@PathVarialbe
是从请求 URI
中提取的变量。您可以将其解压缩并按照您的意愿使用它。
基本上,路径应该描述该 uri 上可用的资源。如果资源不可用,则响应应该是例如NOT_FOUND
。在 Spring
中,对导致 RuntimeException
的请求的默认响应是 5xx
在这种情况下这不是一个好的选择,但这只是一个示例.
如果您有兴趣在 Spring
中处理异常
,只需要求说明即可。
关于java - Spring MVC 中 @RequestMapping() 的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45607211/