views:

1724

answers:

2

Hi All,

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?

+1  A: 

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.

skaffman
Yes, I know this. My problem is that this should be slightly configurable per method. Annotations would be ideal for this because they allow a very simple way to handle that extra parameter.
Tomas Salfischberger
Yeah, I can see that would be restrictive. Another option could be to write your own implemention of HandlerAdapter, perhaps subclassing the AnnotationMethodHandlerAdapter. I've never done this myself, but it may give you the flexibility to do what you need.
skaffman
A: 

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;
Gerrit Brehmer
With the added remark that Solution 2 works for objects not instantiated by Spring when @Configurable is used (requires AspectJ)
Tomas Salfischberger