user755806
user755806

Reputation: 6825

Call spring MVC controller on click of html normal button?

I have below jsp page with one button. On click of the button it has call the controller and the controller has to display the same jsp page. How can i do that?

Controller.java

 @Controller
    @RequestMapping("/status")
    public class CheckController { 


        @RequestMapping(method = RequestMethod.GET)
        public String loadDetails(ModelMap model) {


            List<Data> details = // fetch data from database
            model.addAttribute("details ", details );
            return "Status";
        }

    }


Status.jsp
----------

    <html>
    <body>
            <h2>Spring MVC and List Example</h2>

        <c:if test="${not empty details}">
            <c:forEach var="listValue" items="${details}">
                <table border="1" cellspacing="1" align="center"
                    style="margin-top: 160px;">
                    <tr>
                        <th>Status</th>
                        <th>Message</th>
                        <th>Last Updated</th>
                    </tr>
                    <tr>
                        <td>OK</td>
                        <td>${listValue.message}</td>
                        <td>${listValue.lastChecked}</td>
                    </tr>
                </table>
            </c:forEach>
        </c:if>
<button>Load</button> //on click of button controller has to be called and again same jsp has to be rendered
    </body>
    </html>

Upvotes: 1

Views: 22238

Answers (3)

Florian Fankhauser
Florian Fankhauser

Reputation: 3675

So you need to make another GET request to the same URI. A clean way that doesn't depend on JavaScript is using a form:

<form>
    <button type="submit">Load</button>
</form>

If you dont't specify an action-attribute on the form element, the GET request is made to the same URI as the current page (in HTML5). In HTML4 the action attribute is required, so you can use the following:

<form action="<c:url value="/status" />">
    <button type="submit">Load</button>
</form>

Upvotes: 0

n1ckolas
n1ckolas

Reputation: 4450

If you need to display the same JSP page, then regardless actual URL, you can use something like:

<button onclick="window.location.href=window.location.href;">Load</button>

Also it can be slightly shorter, but please note, that it won't work for old IE versions.

<button onclick="window.location.reload();">Load</button>

Upvotes: 2

Georgy Gobozov
Georgy Gobozov

Reputation: 13731

<button onclick="window.location.href='/status'">Load</button>

if your jsp has form you can submit form to action='/status' url

Upvotes: 3

Related Questions