Spring 3 Web MVC - @Controller method() pre & post processing functionality through annotations

java, spring, spring-mvc

Solution

You can annotate a method with `@ModelAttribute` to execute a method before a controller method. Or use an `interceptor`

Example with `@ModelAttribute`

@Controller    
public class MyController {

    @RequestMapping(value="/someurl", method=RequestMethod.GET)
    public String doStuff(@ModelAttribute("something") Something something, ModelMap map) {
        //do stuff
        // here you can do what you want with something it has been provided to you in the method parameters
        return "someurl";
    }

    @ModelAttribute("something")
    public Something something() {
        // do what you need
        return new Something();
    }
}

The `something()` method will be called before every method having a `@RequestMapping` annotation, thus before the `doStuff()` method.

Problem

I'd like to be able to have the following: ``` @Controller public class MyController { @RequestMapping(value="/someurl", method=RequestMethod.GET) @PreProcess @PostProcess public String doStuff(ModelMap map) { //do stuff return "someurl"; } } ``` The `@PreProcess` and `@PostProcess` are arbitrarily named Annotations. I've been looking for a working example of this but I can't find any. I've looked at AOP and the use of the `@Aspect` annotation but I found it quite complex. A working example of what I'm trying to do would be great. I've sampled Spring Security in the past but this isn't quite what I need because I need the processing to be custom, pretty much anything I want. I know that this functionality is available in .Net MVC. Hoping it's available in Spring also. Any help or pointers really appreciated.

Original source