Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing HttpServletRequest from AOP advice in Spring 2.5 with annotations

I have tried to find the answer to this question on both the Spring forum and by searching StackOverflow. I have found a lot of pages describing horrible architectures and asking for about the same thing as I do, but my intended usage is different so please bear with me :-)

I have a Spring 2.5 project using annotation based form controllers basically like this:

@RequestMapping("/edit/someObject")
public String handleSubmit(HttpServletRequest request, HttpServletResponse response, SomeObject someObject, BindingResult result) {

    // Some check here

    if(result.hasErrors()) {
        return "form";
    } else {
        SomeObjectService.update(someObject);
        return "redirect:/view/someObject";
    }
}

In this I check for some http property in the HttpServletRequest and use the HttpServletResponse to send a redirect if this property has a certain value. This check is done is a lot (but not all) of the form controllers in this application. What I would like to do is create a @CheckedSubmit annotation handled by some AOP advice to do this check and then drop the HttpServletRequest and HttpServletResponse parameters from the controller.

My problem is that I have no idea how to access the current HttpServletRequest and HttpServletResponse from this AOP advice without using these two as (unused) parameters to the annotated method, which is what I tried to avoid in the first place.

Summary: How to access the HttpServletRequest/Response from AOP advice on an @RequestMapping annotated method?

like image 897
Tomas Avatar asked Jun 10 '09 19:06

Tomas


2 Answers

Two solutions for the summary but not for your entire problem (completely)

Solution 1: inside advice (>= Spring 2.0 required)

HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
        .getRequestAttributes()).getRequest();

Solution 2: inside aspect class (probably Spring 3.0 inside singelton beans required!)

@Autowired(required=true)
private HttpServletRequest request;
like image 189
Gerrit Brehmer Avatar answered Sep 28 '22 18:09

Gerrit Brehmer


I think you probably know this already, but the "official" was to do this in Spring MVS is to use HandlerInterceptors. They're not annotation-driven, but they do get inserted into the HTTP control flow, and get full access to the request and response.

like image 29
skaffman Avatar answered Sep 28 '22 17:09

skaffman