Spring MVC:如何指示是否需要路径变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17821731/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring MVC: how to indicate whether a path variable is required or not?
提问by curious1
I am doing a Spring web. For a controller method, I am able to use RequestParam to indicate whether a parameter it is required or not. For example:
我正在做一个 Spring 网络。对于控制器方法,我可以使用 RequestParam 来指示是否需要一个参数。例如:
@RequestMapping({"customer"})
public String surveys(HttpServletRequest request,
@RequestParam(value="id", required = false) Long id,
Map<String, Object> map)
I would like to use PathVariable such as the following:
我想使用 PathVariable 如下:
@RequestMapping({"customer/{id}"})
public String surveys(HttpServletRequest request,
@PathVariable("id") Long id,
Map<String, Object> map)
How can I indicate whether a path variable is required or not? I need to make it optional because when creating a new object, there is no associated ID available until it is saved.
如何指示是否需要路径变量?我需要将其设为可选,因为在创建新对象时,在保存之前没有可用的关联 ID。
Thanks for help!
感谢帮助!
回答by Martin Cmarko
VTTom`ssolution is right, just change "value" variable to array and list all url possibilities: value={"/", "/{id}"}
VTTom 的解决方案是正确的,只需将 "value" 变量更改为数组并列出所有 url 可能性: value={"/", "/{id}"}
@RequestMapping(method=GET, value={"/", "/{id}"})
public void get(@PathVariable Optional<Integer> id) {
if (id.isPresent()) {
id.get() //returns the id
}
}
回答by Tristan
There's no way to make it optional, but you can create two methods with one having the @RequestMapping({"customer"})annotation and the other having @RequestMapping({"customer/{id}"})and then act accordingly in each.
没有办法让它成为可选的,但是你可以创建两个方法,一个有@RequestMapping({"customer"})注释,另一个有@RequestMapping({"customer/{id}"}),然后在每个方法中相应地采取行动。
回答by VTTom
I know this is an old question, but searching for "optional path variable" puts this answer high so i thought it would be worth pointing out that since Spring 4.1 using Java 1.8 this is possible using the java.util.Optional class.
我知道这是一个老问题,但是搜索“可选路径变量”会使这个答案很高,所以我认为值得指出的是,自从 Spring 4.1 使用 Java 1.8 以来,使用 java.util.Optional 类是可能的。
an example would be (note the value must list all the potential routes that needs to match, ie. with the id path variable and without. Props to @martin-cmarko for pointing that out)
一个例子是(注意该值必须列出所有需要匹配的潜在路由,即使用 id 路径变量和不使用。@martin-cmarko 的道具指出这一点)
@RequestMapping(method=GET, value={"/", "/{id}"})
public void get(@PathVariable Optional<Integer> id) {
if (id.isPresent()) {
id.get() //returns the id
}
}
回答by Aniket Thakur
VTToms answer will not work as without id in path it will not be matched (i.e will not find corresponding HandlerMapping) and consequently controller will not be hit. Rather you can do -
VTToms 答案将不起作用,因为路径中没有 id 它将无法匹配(即找不到对应的HandlerMapping),因此控制器不会被命中。相反,你可以这样做 -
@RequestMapping({"customer/{id}","customer"})
public String surveys(HttpServletRequest request, @PathVariable Map<String, String> pathVariablesMap, Map<String, Object> map) {
if (pathVariablesMap.containsKey("id")) {
//corresponds to path "customer/{id}"
}
else {
//corresponds to path "customer"
}
}
You can also use java.util.Optionalwhich others have mentioned but it requires requires Spring 4.1+ and Java 1.8..
您也可以使用java.util.Optional其他人提到的,但它需要 Spring 4.1+ 和 Java 1.8..
回答by Ashutosh
There is a problem with using 'Optional'(@PathVariable Optional id) or Map (@PathVariable Map pathVariables) in that if you then try to create a HATEOAS link by calling the controller method it will fail because Spring-hateoas seems to be pre java8 and has no support for 'Optional'. It also fails to call any method with @PathVariable Map annotation.
使用 'Optional'(@PathVariable Optional id) 或 Map (@PathVariable Map pathVariables) 存在问题,如果您随后尝试通过调用控制器方法创建 HATEOAS 链接,它将失败,因为 Spring-hateoas 似乎已预先java8 并且不支持“可选”。它也无法使用 @PathVariable Map 注释调用任何方法。
Here is an example that demonstrates the failure of Map
这是一个演示 Map 失败的示例
@RequestMapping(value={"/subs","/masterclient/{masterclient}/subs"}, method = RequestMethod.GET)
public List<Jobs> getJobListTest(
@PathVariable Map<String, String> pathVariables,
@RequestParam(value="count", required = false, defaultValue = defaultCount) int count)
{
if (pathVariables.containsKey("masterclient"))
{
System.out.println("Master Client = " + pathVariables.get("masterclient"));
}
else
{
System.out.println("No Master Client");
}
//Add a Link to the self here.
List list = new ArrayList<Jobs>();
list.add(linkTo(methodOn(ControllerJobs.class).getJobListTest(pathVariables, count)).withSelfRel());
return list;
}
}

![spring 获取错误:无法加载 JDBC 驱动程序类 [org.postgresql.Driver]](/res/img/loading.gif)