简体   繁体   中英

How to redirect to another request mapping of a spring MVC controller from a jsp within a jsp

Situation: I have a jsp within a jsp. I load another jsp into a div of the outer jsp using .html(). I want to redirect my url into an entirely new url mapping from a controller.

Sample controller:

@RequestMapping(value = { "/main/submit" }, method = RequestMethod.POST)
public String main(ModelMap model) {
            System.out.println("In controller");

            return "redirect:/anotherJSP";
}

@RequestMapping(value = { "/anotherJSP" }, method = RequestMethod.POST)
public String anotherJSP(ModelMap model) {
            System.out.println("In another");

            return "anotherJSP";
}

Jsp within a jsp:

$.ajax({
    type : "POST",
    url : "/main/submit",
    success : function(msg) {
        console.log('redirect');
    },
    error : function() {
        alert("Error.");
    }
});

Now, the problem is that the outer jsp stays, and the /anotherJSP url only gets loaded in the innerJSP. I wanted to leave the two jsps and go to the new request mapping URL. Is there anyway I can do it? Thanks a lot in advance!

You can't redirect a POST .

When you return redirect:/anotherJSP , the server sends a redirect instruction back to the web browser, and the browser then sends a new GET request for the given URL.

The GET request will be for the URL given, with any query parameters. This means that and POST payload (data) will be lost.

Change @RequestMapping(value = { "/anotherJSP" }, method = RequestMethod.POST) to @GetMapping("/anotherJSP") (assuming Spring 4.3 or later).

Since an ajax call is asynchronous the effect of return "redirect:/anotherJSP"; is not affecting the browser window, instead you should use window.location.href in your ajax call like this:

$.ajax({
    type : "POST",
    url : "/main/submit",
    success : function(msg) {
        console.log('redirect');
        window.location.href = /anotherJSP;
    },
    error : function() {
        alert("Error.");
    }
});

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