简体   繁体   中英

Call controller method from JSP button in Spring MVC

I would like to call a controller method using a button on a JSP page in Spring MVC, but I would like it to stay on a current page, don't reload it or anything, simply call a method. I found it difficult. My button is on cars.jsp page. In order to stay on this page I have to do something like this:

@RequestMapping(value="/start")
public String startCheckingStatus(Model model){
    System.out.println("start");
    model.addAttribute("cars", this.carService.getCars());
    return "car\\cars";
}

button:

 <a href="<spring:url value="/cars/start"/>">Start</a>

But this is not a good solution because my page is actually reloaded. Can I just call controller method without any refreshing, redirecting or anything? When I remove return type like so:

@RequestMapping(value="/start")
public void startCheckingStatus(Model model){
    System.out.println("start");
}

I got 404.

Add an onclick event on your button and call the following code from your javascript:

 $("#yourButtonId").click(function(){
    $.ajax({
        url : 'start',
        method : 'GET',
        async : false,
        complete : function(data) {
            console.log(data.responseText);
        }
    });

});

If you want to wait for the result of the call then keep async : false otherwise remove it.

As mentioned elsewhere you can achieve this by implementing an Ajax based solution:

https://en.wikipedia.org/wiki/Ajax_(programming)

With Ajax, web applications can send data to and retrieve from a server asynchronously (in the background) without interfering with the display and behavior of the existing page. By decoupling the data interchange layer from the presentation layer, Ajax allows for web pages, and by extension web applications, to change content dynamically without the need to reload the entire page .

To achieve this you will need to make changes to both the client and server side parts of your app. When using Spring MVC it is simply a case of adding the @ResponseBody annotation to your controller method which:

can be put on a method and indicates that the return type should be written straight to the HTTP response body (and not placed in a Model, or interpreted as a view name).

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-responsebody

Thus, for example, to return a simple String in the Ajax response we can do the following (without the @ResponseBody the framework would try and find a view named 'some status' which is obviously not what we want):

@RequestMapping(value="/start")
@ResponseBody 
    public String startCheckingStatus(Model model){
    return "some status"; 
}

For the client part you need to add some javascript which will use the XMLHttpRequest Object to retrieve data from your controller.

While there are various frameworks which can simplify this (eg JQuery) there are some examples at the below using vanilla javascript and it might be worth looking at some of these first to see what is actually going on:

http://www.w3schools.com/ajax/ajax_examples.asp

If we take this specific example:

http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_callback

and [1] copy the <button/> and <script/> elements to your JSP, [2] change the URL to point to your controller and, [3] create an element <div id="demo"></div> in your JSP then, on clicking the button in your page, this <div/> should be updated to display the String returned by your controller.

As noted this is a lot of code for one action so you can use some JS framework to abstract a lot of it away.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM