Spring forms controller generalization

When creating a controller for the spring mvc application, I need to specify a new method every time I want to pass new instances of the class from spring forms:

@RequestMapping(method=RequestMethod.POST) public String mainPost(@Valid MyClass myClass, BindingResult result, Model model) { // do the same stuff each time here } 

So, I need to write a method for all possible MyClass in my application
which can be passed to the controller, but all of these methods do exactly the same thing
(they check for errors and pass this object to the service level).

How can I combine all these methods in one?

I believe there is some solution similar to the following (this does not work):

 @RequestMapping(method=RequestMethod.POST) public <T> String mainPost(@Valid T myObject, BindingResult result, Model model) { // check errors and pass the object myObject to a service layer } 
+4
source share
1 answer

You cannot have generic controller methods, but you can create a generic controller:

 public abstract class AbstractController<T> { @RequestMapping(method=RequestMethod.POST) public String mainPost(@Valid T myObject, BindingResult result, Model model) { ... } } @Controller @RequestMapping("/myclass") public class MyClassController extends AbstractController<MyClass> { ... } 
+3
source

All Articles