Reputation: 1496
I want to add an attribute to all my requests before they reach the controller.
What I am using :
@Component
public class SessionValidatorInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
.... some code ....
request.setAttribute("validRequest","true");
.... more code ...
return true;
}
Now to get this attribute in my rest controller I am doing :
public ResponseEntity<?> someMethod(HttpServletRequest request){
request.getAttribute("validSession");
...
My question is can I do this more elegantly like @RequestParam("validSession") or @PathVariable or something else? Can Spring do this for me ?
Appreciate any help.
Upvotes: 0
Views: 2137
Reputation: 124526
In Spring 4.3 the @RequestAttribute
annotation was added just for this.
public void yourMethod(@RequestAttribute("validRequest") boolean valid)
something like that should do the trick.
If you are on an earlier version of Spring you can implement your own HandlerMethodArgumentResolver
to do the same.
Upvotes: 4
Reputation: 2626
Simply use @RequestAttribute
Like this
public ResponseEntity<?> someMethod(HttpServletRequest request,
@RequestAttribute("validSession") String xyz){
}
Since, Mr. Denim didn't post answer, i thought why not me. ^_^
Upvotes: 1