JSP Page Redirection
When you need to move a document to a new location, you use JSP redirection.
The simplest way to redirect is to use the sendRedirect()
method of the response object. The method signature is as follows:
public void response.sendRedirect(String location)
throws IOException
This method sends the status code and the new page location back to the browser. You can also achieve the same effect using the setStatus()
and setHeader()
methods:
....
String site = "http://www.tutorialpro.org" ;
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site);
....
Example Demonstration
This example demonstrates how JSP performs page redirection:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.io.*,java.util.*" %>
<html>
<head>
<title>Page Redirection</title>
</head>
<body>
<h1>Page Redirection</h1>
<%
// Redirect to a new address
String site = new String("http://www.tutorialpro.org");
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site);
%>
</body>
</html>
Save the above code in a file named PageRedirecting.jsp
, and then access http://localhost:8080/PageRedirect.jsp
. It will redirect you to http://www.tutorialpro.org/.