Search code examples
javaformsjspspring-mvcspring-roo

How can use the same method in a controller, receiving an abstract class?


I have 5 different jsp with mvc spring forms. In modelAttribute of each form, I have a specific class (for example, dog, cat, mouse, etc). Each form has a submit button, and I want that request will submit in the same method in the controller.
In the controller, I try to get a general class (abstract) such animal. And it gives me an error. How could i do this?

If a receive a cat, this works fine. Thanks!

the jsp:

<form:form method="post" modelAttribute="Cat" action="../2/submit">
            <form:checkbox path="attribute" />
            <button type="submit">Submit</button>
</form:form>

and the controller:

@RequestMapping(value = "/submit",  produces ="text/html" ,headers = "Accept=" ,  method=RequestMethod.POST) 
    public String submitForm(@ModelAttribute Animal animal, Model m) throws IllegalArgumentException, IllegalAccessException {
        return "";
    }

Solution

  • I can think of two techniques for this.

    Technique: Old School

    Use a parameter of type WebRequest in the handler method. This gives access to the request parameters. Then you query the parameters you care about to determine the source of the request and to determine the parameters that you require.

    @RequestMethod("/blammy")
    public String blammy(
        final ModelMap model,
        final WebRequest webRequest)
    {
        String something = webRequest.getParameter("something");
    
        if ("hoot".equals(something))
        {
            ... process a hoot request
        }
        else if ("bark".equals(something))
        {
            ... process a bark request
        }
    }
    

    Technique: Front Controller

    Proved a method for each form then forward the call to a common method.

    @RequestMethod("/fish")
    public String fish(
        @ModelAttribute final Fish fish,
        final ModelMap model)
    {
         return commonMethod(model, (Animal)fish);
    }
    
    @RequestMethod("/cat")
    public String cat(
        @ModelAttribute final Cat cat,
        final ModelMap model)
    {
         return commonMethod(model, (Animal)cat);
    }
    
    public String commonMethod(
        final ModelMap model,
        final Animal animal)
    {
        ... blam
    }