Reputation: 85382
Is it possible to somehow get a hold of a @PathVariable
in a @ControllerAdvice
given that the PathVariable is only present in some requests?
If this was in a Controller, I could write 2 different Controllers. But a ControllerAdvice
always applies to all requests. I can't have a ControllerAdvice apply to only Controllers where the PathVariable is defined.
Upvotes: 2
Views: 1898
Reputation: 317
this answer is ok, but it took me a while to found out that you need to add the @ModelAttribute annotation before the function. Also is good to know that you can inject any variable that you use in the controller @RequestMapping side. So for example the whole class will look like
@ControllerAdvice(basePackages = {"test.web.controller"})
public class SomeAdvicer {
@ModelAttribute
public void advise(@PathVariable Map<String, String> pathVariables, SomeOtherClass ctx) {
if (pathVariables.containsKey("something")) {
if (!pathVariables.get("something").equals(ctx.getSomething())){
throw new Exception("failed");
}
}
}
}
When your controller looks like
@RequestMapping(method = RequestMethod.PUT, value = "/{something}")
@ResponseBody
public ResponseEntity<test> updateDemo(
@PathVariable(value = "invoicerId")
@RequestBody RequestMessage requestBodyMessage,
SomeOtherClass ctx) throws RestException { .... }
Upvotes: 1
Reputation: 984
You can inject the Map of path variables and check for the existence of a key.
public void advise(@PathVariable Map<String, String> pathVariables) {
if (pathVariables.containsKey("something")) {
String something = pathVariables.get("something");
// do something
} else {
// do something else
}
}
Upvotes: 3