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
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With