简体   繁体   English

使用Spring 4.2,我如何将路径变量作为可选项

[英]With Spring 4.2 how can i make the path variable as optional

@RequestMapping(value="/return/{name}",method=RequestMethod.GET)
public ResponseEntity<String> ReturnName(HttpServletRequest req,@PathVariable(name) String inputName) {
    return new ResponseEntity<>(inputName, HttpStatus.OK)
}

I have found the solution like 我找到了解决方案

@RequestMapping(value="/return/{name}",method=RequestMethod.GET)
public ResponseEntity<String> ReturnName(HttpServletRequest req,@PathVariable(name) Optional<String> inputName) {
    return new ResponseEntity<>(inputName.isPresent() ? inputName.get() : null, HttpStatus.OK)
}

But it is not working as expected. 但它没有按预期工作。

It throws 405 if the value for name is not give. 如果没有给出name的值,则抛出405。

Example : 示例:

return/ram is working fine. return / ram工作正常。

return throws 405 error. 返回抛出405错误。

Whether i am missing anything? 我是否遗漏了什么?

Is there any spring property to handle this? 有没有弹簧属性来处理这个?

Thanks in advance. 提前致谢。

您不能,只需创建另一种方法来捕获URL中没有{name}的URL。

@RequestMapping(value="/return",method=RequestMethod.GET)

To make your own proposed solution work and use a single method, you can use like this: 要使您自己提出的解决方案工作并使用单个方法,您可以像这样使用:

@RequestMapping(value= {"/return/{name}", "/return"},method=RequestMethod.GET)
public ResponseEntity<String> ReturnName(HttpServletRequest req, @PathVariable("name") Optional<String> inputName) {
    return new ResponseEntity<>(inputName.isPresent() ? inputName.get() : null, HttpStatus.OK);
}

In the end it is still 2 endpoints like Baldurian proposed. 最后它仍然是像Baldurian提出的2个端点。

Try this: 尝试这个:

@RequestMapping(value= {"/return/{name}", "/return"},method=RequestMethod.GET)
public ResponseEntity<String> ReturnName(HttpServletRequest req, @PathVariable("name") Optional<String> inputName) {
    return new ResponseEntity<>(inputName.isPresent() ? inputName.get() : null, HttpStatus.OK);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM