Pr.Pg Next Pg

Page Redirection

  • Page redirection is generally used for moving to new page or location with new url address.

  • sendRedirect() method of response object provide the simple mechanism for redirecting the request to new page.

  • sendRedirect() method redirect the response to another resource. sendRedirect() method actually makes the client(browser) to create a new request to get to the resource. The client can see the new url in the browser.

 

Example: Servlet program of page redirection using sendRedirect

Sam Sir

//Program name Redirect.java

// Program of page redirection using sendRedirect

 

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

 

public class Redirect extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType(“text/html;charset=UTF-8”);

PrintWriter out = response.getWriter();

try {

response.sendRedirect(“http://www.google.com”);

}finally {

out.close();

}

}

}

Output

Page Redirect

 

 

Example: Servlet program to redirect page using setHeader

Sam Sir

//Program name RedirectsetHd.java

// Program to redirect page using setHeader

 

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

public class RedirectsetHd extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

 

PrintWriter out = response.getWriter();

 

response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);

response.setHeader(“Location”, “http://www.google.com”);

response.setContentType(“text/html”);

return;

}

}

Output

setHeader

 

Different between SendRedirect and setHeader

Sr No

setHeader

sendRedirect

1

setHeader Sets a response header with the given name and value.

sendRedirect Sends a temporary redirect response to the client using the specified redirect location URL and clears the buffer.

2

If the header had already been set, the new value overwrites the previous one.

sendRedirect cannot send any information except new URL to the browser.

3

setHeader contains two parameter name and value

sendRedirect contain one parameter as a URL location.

Pr.Pg border                                              Next Pg