I am trying to migrate from Spring 2.0 to Spring 3.0.
Previously I defined a controller MyController
inheriting from SimpleFormController
and have some logic written in the onSubmit
method. All my controllers having the handler methods are inherited from MyController
. Thus, the logic written in onSubmit
of MyController
used to get executed for all requests.
Now as I migrate to annotated controller wherein my controller is a simple pojo, how do I ensure the execution of onSubmit
everytime? One way is to call onSubmit
from all handler methods of all the controllers. This is cumbersome.
Can anyone suggest any feasible solution. As annotating formBackingObject
with @ModelAttribute
ensures the invocation for all requests, isn't there an analogy for onSubmit
method?开发者_如何学Python
If you want to perform the same action before each invokation of any annotated controller, you could use an interceptor. You can write your own interceptor by just implementing the preHandle method. You will then need to register this interceptor in the DefaultAnnotationHandlerMapping or whatever Handler mapping you use to dispatch to your controllers. Registering interceptors is explained in this article: http://www.scottmurphy.info/spring_framework_annotation_based_controller_interceptors
Annotate the method you wish to invoke. The method signature is very flexible. Take a look at the docs for @RequestMapping
@RequestMapping(value={"/foo"}, method=RequestMethod.POST)
public String myMethod(many options for parameters) {...
Ok so if i understand correctly you want inheritance to continue to play a role in the stack when a request is handled by a controller. You can extend any class in an @RequestMapping annotated POJO but you will have to define an @override method to annotate it. All you do basically is call super with the arguments in the overriding method. If you extend an annotated class and both are declared as Controller then you will get an exception since the route will be defined more then once.
it would look like this
public class Pojo{
public String someBaseMethod(){
return "";
}
}
@Controller
public class ChildController extends Pojo {
@Override
@RequestMapping("/do_it")
public String someBaseMethod() {
return super.someBaseMethod();
}
}
A good case could be made to use composition over inheritance. I even suggest that you use the filtering mechanism instead if it can apply to perform common operations. AOP could also be a good tool.
精彩评论