codeomnitrix codeomnitrix - 2 months ago 11
Java Question

Redirecting a request using servlets and the "setHeader" method not working

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", "")

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

import javax.servlet.*;
import javax.servlet.http.*;

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

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

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
else if(name == null){//first line of header{
System.out.println("Server HTTP version, Response code: ");
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){

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 :
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:)

Answer Source

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