[java] 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", "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:)

This question is related to java tomcat servlets header

The answer is


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

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

}

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

Alternatively, you could try the following,

resp.setStatus(301);
resp.setHeader("Location", "index.jsp");
resp.setHeader("Connection", "close");

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to tomcat

Jersey stopped working with InjectionManagerFactory not found The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. on deploying to tomcat Spring boot: Unable to start embedded Tomcat servlet container Tomcat 404 error: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists Spring Boot application in eclipse, the Tomcat connector configured to listen on port XXXX failed to start Kill tomcat service running on any port, Windows Tomcat 8 is not able to handle get request with '|' in query parameters? 8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE 403 Access Denied on Tomcat 8 Manager App without prompting for user/password Difference between Xms and Xmx and XX:MaxPermSize

Examples related to servlets

Google Recaptcha v3 example demo Difference between request.getSession() and request.getSession(true) init-param and context-param java.lang.NoClassDefFoundError: org/json/JSONObject how to fix Cannot call sendRedirect() after the response has been committed? getting error HTTP Status 405 - HTTP method GET is not supported by this URL but not used `get` ever? Create a simple Login page using eclipse and mysql Spring get current ApplicationContext insert data into database using servlet and jsp in eclipse What is WEB-INF used for in a Java EE web application? No 'Access-Control-Allow-Origin' header in Angular 2 app How to add header row to a pandas DataFrame How can I make sticky headers in RecyclerView? (Without external lib) Adding header to all request with Retrofit 2 Python Pandas Replacing Header with Top Row Request header field Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers Pythonically add header to a csv file fatal error C1010 - "stdafx.h" in Visual Studio how can this be corrected? correct PHP headers for pdf file download How to fix a header on scroll