简体   繁体   中英

Why the response.sendRedirect() in servlet doesn't work after receiving the post request of JQuery?

In the blog-edit.html, JQuery was used to send the post request to the sever side(java servlet).

$("#btn").click(function() {
                    $.post("/blog/handler",{"content":$('#textarea').val()},
                    function(data){
                        alert("Data Loaded: " + data);
                        if(data.toString().length>1){
                            alert("Saved!")
                        }else{
                            alert("Failed!")
                        }
                    })

In the server side:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String content = request.getParameter("content");
            System.out.println(content);

            response.sendRedirect("/blog/list");
            return;
    }

What I saw is the server side is printing the content from the html, and the alert window pops up to say "Saved!". But the redirect function doesn't work

After searching I have no choice but to use jquery to redirect:

if(data.toString().length>1){
                            alert("Saved!")
                            window.location.replace("/blog/list")
                        }

it works, but it's not what i want

please help

While using ajax. you can not execute server side redirect.

However, there are better way how to redirect on client in such a scenario.

See Here

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