Redirecting a request using servlets and the “setHeader” method not working

后端 未结 4 780
情深已故
情深已故 2020-12-03 02:57

I am new to servlet development, and I was reading an ebook, and found that I can redirect to a different web page using

setHeader(\"Location\", \"http://ww         


        
相关标签:
4条回答
  • 2020-12-03 03:27

    As you can see, the response is still HTTP/1.1 200 OK. To indicate a redirect, you need to send back a 302 status code:

    response.setStatus(HttpServletResponse.SC_FOUND); // SC_FOUND = 302
    
    0 讨论(0)
  • 2020-12-03 03:39

    Oh no no! That's not how you redirect. It's far more simpler:

    public class ModHelloWorld extends HttpServlet{
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
            response.sendRedirect("http://www.google.com");
        }
    }
    

    Also, it's a bad practice to write HTML code within a servlet. You should consider putting all that markup into a JSP and invoking the JSP using:

    response.sendRedirect("/path/to/mynewpage.jsp");
    
    0 讨论(0)
  • 2020-12-03 03:45

    Another way of doing this if you want to redirect to any url source after the specified point of time

    import javax.servlet.ServletException;
    
    import javax.servlet.http.HttpServlet;
    
    import javax.servlet.http.HttpServletRequest;
    
    import javax.servlet.http.HttpServletResponse;
    
    import java.io.*;
    
    public class MyServlet extends HttpServlet
    
    
    {
    
    public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException
    
    {
    
    response.setContentType("text/html");
    
    PrintWriter pw=response.getWriter();
    
    pw.println("<b><centre>Redirecting to Google<br>");
    
    
    response.setHeader("refresh,"5;https://www.google.com/"); // redirects to url  after 5 seconds
    
    
    pw.close();
    }
    
    }
    
    0 讨论(0)
  • 2020-12-03 03:50

    Alternatively, you could try the following,

    resp.setStatus(301);
    resp.setHeader("Location", "index.jsp");
    resp.setHeader("Connection", "close");
    
    0 讨论(0)
提交回复
热议问题