简体   繁体   中英

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.

Example :

return/ram is working fine.

return throws 405 error.

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.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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