Reputation: 503
I have a controller that handles few requests that have to be checked for existence of the same cookie value. This means that in each request handler I have to perform the same check.
@Controller
public class MyController {
@RequestMapping("/Path")
public String Handler1(@CookieValue(required = false, value = "Cookie") String cookie) {
if (cookie != null) {
handleNoCookie();
}
handleRequest1();
}
@RequestMapping("/AnotherPath")
public String Handler2(@CookieValue(required = false, value = "Cookie") String cookie) {
if (cookie != null) {
handleNoCookie();
}
handleRequest2();
}
and so on...
}
Is there a way to extract the duplicated check this into some method that will do the check before the actual handler executes?
Thanks.
Upvotes: 1
Views: 3078
Reputation: 11386
AOP interceptor suggested in other answers is an configurational overkill.
Similar functionality can be achieved using @ModelAttribute annotation. It is available since Spring 2.5. Methods annotated using @ModelAttribute
must generate parameters for the view model. These methods are called before every method annotated using @RequestMapping
.
It seems to be working if the annotated method returns nothing (void-method). In this case it works as some imaginary "BeforeEveryRequest" annotation. It looks like this:
@ModelAttribute
public void tagController(HttpServletRequest request) {
request.setAttribute(VERSION_PARAMETER, version());
}
UPDATE:
There is a small side effect. It adds a dummi value to the model. Key is a string "void" and the value is null
.
Upvotes: 0
Reputation: 5871
You could use an interceptor to ... "intercept" requests and process your logic if the cookie isn't there. You can make it fire before the controller is hit via the preHandle method.
API: HandlerInterceptor
Upvotes: 2
Reputation: 1554
If there are a large number of Handler methods, you could look into Spring's AOP to implement the cookie check advice for all the methods.
http://static.springsource.org/spring/docs/2.5.x/reference/aop.html
Upvotes: 1