Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 288
macemers Avatar asked May 23 '12 02:05

macemers


People also ask

How does Response sendRedirect work?

sendRedirect() method redirects the response to another resource, inside or outside the server. It makes the client/browser to create a new request to get to the resource. It sends a temporary redirect response to the client using the specified redirect location URL.

What is the difference between response sendRedirect () and request forward ()?

The main difference between the forward() and sendRedirect() methods is that in the case of forward(), redirect happens at the server end and is not visible to the client, but in the case of sendRedirect(), redirection happens at the client end and it's visible to the client.

How sendRedirect () method of HttpServletResponse differ with forward () method of RequestDispatcher?

The forward() method is faster than sendRedirect() method. The sendRedirect() method is slower because when new request is created old request object is lost. It is declared in RequestDispatcher interface. It is declared in HttpServletResponse.

How do you pass variables in response sendRedirect?

If you forward the request, you can use setAttribute to put your variable in the request scope, which can easily be retrieved in your JSP. response. sendRedirect(urlEncoded); Hope this helps.


1 Answers

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

like image 183
Raab Avatar answered Oct 02 '22 09:10

Raab