문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

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

@RequestMapping(
    value = "/add/email",
    method = { RequestMethod.POST, RequestMethod.PUT } )
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top