Reputation: 818
@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
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
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
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