Question

I have a controller method with RequestMapping.PUT and having a URI

@RequestMapping(value = "/add/email", method = RequestMethod.POST)
public String addNewAccountEmail(@Valid @ModelAttribute EmailClass emailObject, BindingResult bindingResult, Model model) {
    return displayForm(model);
}

I have a form like :

<form:form id="add-user-email" action="/add/email" name="manageUserAddEmail" method="post" modelAttribute="accountEmail">

I want to have more form pointing to same action , but need to do different operations inside addNewAccountEmail method. So how can I achieve this in Spring ? Basically any parameter which can make me differentiate functionalities or somehow I can have multiple methods having same RequestMapping URL and Method ?

I can only use RequestMethod.POST as I have similar requirements for other methods as well.

Basically I do not want the URL to change in Browser when invoking actions, that is why I want all form actions to point to same action URL.

Was it helpful?

Solution

You could point all of your forms at the same controller method and then differentiate the form-specific functionality within that method by looking for form-specific request parameters.

Each form would need to add its own request parameter to identify it - such as:

<input type="hidden" name="form1_param" value="1"/>

And then you can vary the behaviour inside the method by inspecting the HttpServletRequest:

@RequestMapping(value = "/add/email", method = RequestMethod.POST, )
public String addNewAccountEmail(@Valid @ModelAttribute EmailClass emailObject, BindingResult bindingResult, Model model, HttpServletRequest request) {

    if (request.getParameter("form1_param") != null) { // identifies 1st form
        // Do something
    } else if (request.getParameter("form2_param") != null) { // indentifies 2nd form
        // Do something else
    }

    ...
}

It would be cleaner however to have multiple controller methods mapped to the same path, but specify different params in the RequestMapping - to differentiate the different forms.

@RequestMapping(value = "/add/email", params="form1_param", method = RequestMethod.POST)
public String addNewAccountEmail1(@Valid @ModelAttribute EmailClass emailObject, BindingResult bindingResult, Model model) {

    // Do something specific for form1
    return displayForm(model);
}

And also:

@RequestMapping(value = "/add/email", params="form2_param", method = RequestMethod.POST)
public String addNewAccountEmail2(@Valid @ModelAttribute EmailClass emailObject, BindingResult bindingResult, Model model) {

    // Do something specific for form2
    return displayForm(model);
}

Etc.

OTHER TIPS

@RequestMapping accepts arrays as parameters (with an or semantic).

@RequestMapping(
    value = "/add/email",
    method = { RequestMethod.POST, RequestMethod.PUT } )
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top