devanathan
devanathan

Reputation: 818

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.

Upvotes: 2

Views: 359

Answers (3)

user6535685
user6535685

Reputation:

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

Upvotes: 1

dambros
dambros

Reputation: 4392

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.

Upvotes: 4

Matteo Baldi
Matteo Baldi

Reputation: 5828

You can't, simply create another method to catch the url without the {name} in the URL.

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

Upvotes: 3

Related Questions