ZZ 5
ZZ 5

Reputation: 1964

Handling multiple forms, Spring

I'd like to ask you what's the best way (if possible at all) to handle multiple forms on the same page with different methods? Let me explain: I've got a page with three forms. With request mapping path set to 'foo' and method to post they'll be all handled by one method. Is there any way to handle form1 with method1, form2 with method2 etc?

Upvotes: 1

Views: 4673

Answers (2)

Khush
Khush

Reputation: 863

My preferred way would be to create a JSON object using jquery. Serialize all the forms into an object on submit and then pass that json object to the REST controller in spring. That way you can have one controller for all three forms.

Upvotes: 2

m4rtin
m4rtin

Reputation: 2475

As you probably know, HTML forms are submitted to the URL specified by the action attribute so you can easily assign different handler method to different URL so each method can handle a particular form. Example :

Your view (accessed from your /foo URL) :

<html>
<head>
    <!-- bla bla bla -->
</head>

<body>

    <form>
        <!-- without any action specified, forms are submitted to the same URL -->
    </form>

    <form action="?bar2">
        <!-- 2nd form to be handled by method2 -->
    </form>

    <form action="?bar3">
        <!-- 3rd form to be handled by method3 -->
    </form>

</body>
</html>

Your Controller :

@Controller
@RequestMapping("/foo")
public class MyController {

    @RequestMapping
    public void method1(/* anything you want Spring MVC to get for you like form1 backing bean for example */) {
        // handling form1 submission
    }

    // form action attribute must have a "bar2" query param somewhere
    @RequestMapping(params = "bar2") 
    public void method2(/* anything regarding form2 this time */) {
        // handling form2 submission
    }

    @RequestMapping(params = "bar3") 
    public void method3(/* anything regarding form3 this time */) {
        // handling form3 submission
    }
}

As you can see, the thing is to use a differentiating factor, whatever it is (here I used a query param), for Spring to know where the form submission should be handled. If 2 handler methods map to the same URL, Spring will raise you an exception (at runtime) so you have to use one (ideally a meaningful one but sometimes it just exists for the sake of having multiple forms handled from the same root URL, here "/foo").

Upvotes: 5

Related Questions