k-wolski
k-wolski

Reputation: 3

Spring - form with 2 buttons sending to 2 different controllers

I have Spring 4 MVC form with 2 submit buttons. I want these buttons to point to two different controllers. The problem is that one form should have fixed action parameter set. This is my form:

<form:form method="post" action="pageAction" commandName="id">
  <button type="submit" class="btn btn-primary" name="addBasket">
    Add Basket
  </button>
  <button type="submit" class="btn btn-danger" name="addProduct">
    Add Product
  </button>
</form:form>

Is it possible that these button will reach two different controllers? I am going to send only ID, in addBasket it would be basketId, in addProduct it would be productId. These are the controllers:

@Controller
public class BasketController {

    @RequestMapping(value = "/addBasket", method = RequestMethod.POST)
    public ModelAndView addBasket(@ModelAttribute("id") Integer id) {
        //method - addBasket(id);
    }
}

@Controller
public class ProductController {

    @RequestMapping(value = "/addProduct", method = RequestMethod.POST)
    public ModelAndView addProduct(@ModelAttribute("id") Integer id) {
        //method - addProduct(id);
    }
}

Upvotes: 0

Views: 254

Answers (3)

user871199
user871199

Reputation: 1520

If you are using html 5 and compatible browsers, you can use form and formaction attributes of buttons to target according to your needs. See details at w3schools

Upvotes: 1

Kuldeep S Chauhan
Kuldeep S Chauhan

Reputation: 252

You can add an onclick event on the submit button, which would call the a javascript function wherein you could decide/change the url as per the requirement.

<button type="submit" class="btn btn-primary" name="addBasket" onClick="javascript:addBasket()">

<button type="submit" class="btn btn-primary" name="addProduct" onclick="javascript:addProduct()">

Add any number of javascript functions like:

function addBasket() {
var requestURL = '/addBasket';
var formData = $("#formName").serialize();

$.ajax({
    type: 'POST',
    data: formData,
    url: requestURL,
    success: function (data1) {
     //do what is required after success
    },
    error: function (xhr) {
        //in case of failure
    }
});

}

Upvotes: 0

ordonezalex
ordonezalex

Reputation: 2744

I am not sure if there is a solution you want, but an alternative might be to use an if statement in /addItem checking the value of name:

@Controller
public class ItemController {

    @RequestMapping(value = "/addItem", method = RequestMethod.POST)
    public ModelAndView addItem(@ModelAttribute("id") Integer id, @ModelAttribute("name") String name) {
        if ("basket" == name) {
            basketController.addBasket(id);
        } else {
            productController.addProduct(id);
        }
    }
}

Upvotes: 0

Related Questions