My Servlet – “ImportFile”:
doPost(){ ... ... PrintWriter out = response.getWriter(); response.setContentType("text/html"); if(status.equals("Fail")) { out.println("<script type="text/javascript">"); out.println("alert('Import Failed !');"); out.println("</script>"); }else { out.println("<script type="text/javascript">"); out.println("alert('Import Sucessfull !');"); out.println("</script>"); } //response.sendRedirect(request.getContextPath()); out.flush(); }
after Succes or Fail, this is landing on /ImportFile page which isn’t there. What shall I do to redirect it to ContextPath?
Advertisement
Answer
sendRedirect add an HTTP header “Location”, interpreted by the browser so it automatically redirect to the given location.
So if you call the method after sending data, headers are already sent and cannot work.
Try calling the method before any output.
But a redirect response is not supposed to have any body, because browsers may ignore it if a redirection is specified. If you want first to display your message in javascript, do the redirect in javascript like:
out.println("location.href = "" + request.getContextPath() + "";");
just after your alert:
PrintWriter out = response.getWriter(); response.setContentType("text/html"); out.println("<html><body>"); out.println("<script type="text/javascript">"); if(status.equals("Fail")) { out.println("alert('Import Failed !');"); }else { out.println("alert('Import Sucessfull !');"); } out.println("location.href = "" + request.getContextPath() + "";"); out.println("</script>"); out.println("</body></html>"); out.flush();