26

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://www.google.com")

But this is not working, as I have written this code as:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ModHelloWorld extends HttpServlet{
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
//              response.addHeader("Location", "http://www.google.com");
                response.setHeader("Location", "http://www.google.com");
                response.setContentType("text/html");
                PrintWriter pw = response.getWriter();
                pw.println("<html><head><title>Modified Hello World</title></head><body>");
                pw.println("<h1>");
                //getInitParameter function reads the contents ot init-param elements.
                pw.println(getInitParameter("message"));
                pw.println("</h1>");
                pw.println("</body></html>");
                pw.close();
        }
}

i have checked the headers using my program to get the headers of the webpage which is as under:

import java.net.*;
import java.io.*;
class getHeaders{
    public static void main(String args[]){
        URL url = null;
        URLConnection urc = null;
        try {
            url = new URL(args[0]);
            urc = url.openConnection();
            for(int i=0 ; ; i++) {
                String name = urc.getHeaderFieldKey(i);
                String value = urc.getHeaderField(i);
                if(name == null && value == null)//both null so end of header
                    break;
                else if(name == null){//first line of header{
                    System.out.println("Server HTTP version, Response code: ");
                    System.out.println(value);
                    System.out.println("ENd of first header field");
                } else {
                    System.out.println("name of header is: " + name + " and its value is : " + value);
                }
            }
        } catch(MalformedURLException e){
            System.out.println("Malformed URL " + e.getMessage());
        } catch(IOException e){
            e.printStackTrace();
        }
    }
}

And i am getting the output as:

Server HTTP version, Response code: 
HTTP/1.1 200 OK
ENd of first header field
name of header is: Server and its value is : Apache-Coyote/1.1
name of header is: Location and its value is : http://www.google.com
name of header is: Content-Type and its value is : text/html
name of header is: Content-Length and its value is : 101
name of header is: Date and its value is : Sat, 05 Mar 2011 15:27:29 GMT

But I was not redirected to google's page from my browser.

Thanks in advance:)

nbro
  • 15,395
  • 32
  • 113
  • 196
codeomnitrix
  • 4,179
  • 19
  • 66
  • 102
  • This queztion is for the case of a GET method. For the case of a POST, and for some subtleties about the Location header, see the related question http://stackoverflow.com/questions/5043902/whats-the-proper-way-to-set-the-location-header-for-an-http-201-response-in-a-j – Raedwald Jun 24 '13 at 23:22

4 Answers4

70

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");
adarshr
  • 61,315
  • 23
  • 138
  • 167
  • ok thanks adarshr. i think thats fine but was not the thing i was looking for. actually i was trying to redirect to a page using a header. but still another way discovered, thats why very thank you. – codeomnitrix Mar 05 '11 at 15:48
  • 10
    sendRedirect uses the http-header. Implementations of HttpServletResponse usually use .setStatus() and .addHeader(). It even makes relative URLs absolute. So using .sendRedirect() is less code and easier to read. :-) – Boris Mar 05 '11 at 16:16
  • 2
    +1 for the simpler redirect code. But given the 'Hello World' nature of the program, maybe one could be gentler about separation of concerns. – alttag Feb 15 '16 at 18:27
23

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
casablanca
  • 69,683
  • 7
  • 133
  • 150
1

Alternatively, you could try the following,

resp.setStatus(301);
resp.setHeader("Location", "index.jsp");
resp.setHeader("Connection", "close");
Sairam
  • 29
  • 3
-2

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();
}

}
Community
  • 1
  • 1
Pratik
  • 79
  • 1
  • 8