response.sendRedirect() does not running - Servlet

时间:2015-11-12 10:54:39

标签: java servlets response getattribute

When run the below code and the output I receive is "in", but the response .sendRedirect() does not run. The two java servlet files "Class1" and "Servlet1" are in the same folder.

public class Class1 extends HttpServlet {

   public void doGet(HttpServletRequest request, HttpServletResponse response) 
   throws IOException, ServletException {

       response.setContentType("text/html; charset=ISO-8859-7");
       PrintWriter out = new PrintWriter(response.getWriter(), true);

       ArrayList list2 = (ArrayList)request.getAttribute("list_lo");

       if (list2 == null || list2.isEmpty() ) {
          out.println("in");
          response.sendRedirect("Servlet1");
          return;}
       }


}

2 个答案:

答案 0 :(得分:0)

Try to put the name of the file with the extension instead of the class name, sometimes happened to me, and just by doing this worked

答案 1 :(得分:0)

You cannot send redirect once you start returning any output.

You need to put the logic handling any possible redirects before any output is started (e.g. out.println() in your example). Putting the redirect logic at the very beginning of the method is a sensible thing to do anyways, since it should be the first thing you decide.

The reason why redirecting after output is started lies in the HTTP protocol itself - redirect is transmitted using response headers, which are separated from response body by a blank line. Once you start writing the response body, there's no way to transmit any more headers anymore (apart from the started output being still in buffer if you're lucky).