Pass parameter from Button to Java spring MVC controller

fabiang81 picture fabiang81 · Mar 9, 2016 · Viewed 8.4k times · Source

I've been looking for something that might help me to solve this without success. What I need is just to call a Spring Controller by pressing a Button element, and pass from it a RequestParam("statusId" in this specific case). Is there a way to do this without using JavaScript?

I have the next html:

               <div class="tablero col-lg-4 col-md-4 col-sm-6">
                <div class="inner-content">
                    <div class="rate">
                        <div class="number">
                            <span>${package}</span>
                            <span class="text">REFERRALS</span>
                        </div>
                    </div>
                    <div class="description">
                        <h3>
                        <i class="fa fa-shopping-bag"></i>
                        PACKAGE
                    </h3>
                        <label>Paquete</label>
                        <button class="btn-primary" onclick="location.href='listReferred.htm' id="package">GO TO LIST</button><!--The parameter should be send from this button-->
                    </div>
                </div>
            </div>

And the Spring MVC Controller:

@SuppressWarnings("unchecked")
@RequestMapping(value="/listReferred", method=RequestMethod.GET)
public String getListReferredPage(@RequestParam int statusId, Model model) {

    RestTemplate restTemplate = new RestTemplate();
    String url = URL_REFERREDTYPE_JSON+statusId;
    List<SearchProspectTO> searchProspectToList = restTemplate.getForObject(url, List.class, statusId);
    model.addAttribute("searchProspectToList", searchProspectToList);

    return "portalInternoReferidos";
}

Answer

MyBrainHurts picture MyBrainHurts · Mar 9, 2016

Surround at least the button element with a form, like this:

<form action="listReferred" method="get">
    <button...
</form>

Add a name and value attribute to the button:

<button name="yourButton" value="[provide status id here]">GO TO LIST</button>

Alter @RequestParam int statusId to @RequestParam(value="yourButton") int statusId.

This will work except for older IE browsers - below Version 10 I think. These versions will return 'GO TO LIST' instead of the value.

As workaround you could use a hidden input, that has to be placed inside the form section as well.