Vijay
Vijay

Reputation: 384

Spring MVC JSP Jquery call controller method on button click post redirect error

In Spring MVC, I have buttons in my jsp page, on button click, I want to perform some task (controller method), which doesn't return anything. I want to show the same page. It shouldn't reload the page nor should redirect to some other page.

Here's what I am doing...

  1. I have a page with lots of buttons. I am using bootstrap css and button tag. like,

    Start

  2. On this button click, I am calling an Ajax to the method from controller,

        $('#startApp').click(function() {
        BootstrapDialog.show({
            message : 'Sure ?!',
            buttons : [ {
                label : 'Ok',
                cssClass : 'btn-default',
                action : function(dialogItself) {
                    $.ajax({
                        type : "POST",
                        url : "/MyApp/startApp",
                        success : function(response) {
                            alert("Success");
                        }
                    });
    
                    dialogItself.close();
                }
            }, {
                label : 'Close',
                action : function(dialogItself) {
                    dialogItself.close();
                }
            } ]
        });
    
  3. This calls the controller method,

         @RequestMapping(value = "/startApp", method = RequestMethod.POST)
            public void start() {// some operation.}
    
  4. However, when I do this, operation is performed but in logs I am getting below error,

    root cause dispatcher: com.ibm.ws.jsp.webcontainerext.JSPErrorReport: JSPG0036E: Failed to find resource /WEB-INF/views/startApp.jsp

Questions,

Upvotes: 1

Views: 5552

Answers (2)

Lakatos Gyula
Lakatos Gyula

Reputation: 4160

You need to return something to the client. Spring default tries to send back startApp.jsp because that's what in the url (/startApp). Try this: this will send back an HTTP OK status (200).

@RequestMapping("/startApp", method = RequestMethod.POST)
public ResponseEntity start()
{
    return new ResponseEntity(HttpStatus.OK);
}

You can also send back a json by returning a POJO (it'll be automatically serialized by the Jackson JSON lib) if that's what you want, or even a simple string as the html content by returning a String.

Upvotes: 1

Santhosh
Santhosh

Reputation: 8207

The purpose of ajax is to refresh a part of page. so re-directing to another page is meaningless, you could make the return type as String in your controller.

@RequestMapping(value = "/startApp", method = RequestMethod.POST)
@ResponseBody
        public String start() {
        // some operation
        return "sucess"
        }

Read my answer here Returning Hashmap From controller to JSP in Springmvc to know how to pass parameters in response

Upvotes: 0

Related Questions