JSP Redirect Example

JSP Redirect: In JSP Redirect URL is changed and it is slower than JSP Forward.
Page redirection is generally used when a document moves to a new location and we need to send the client to this new location or may be because of load balancing, or for simple randomization.The simplest way of redirecting a request to another page is using method sendRedirect() of response object. Following is the signature of this method:

public void response.sendRedirect(String location)
throws IOException

This method sends back the response to the browser along with the status code and new page location. You can also use setStatus() and setHeader() methods together to achieve the same redirection:

....
String site = "https://www.dineshonjava.com" ;
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site); 
....

JSP Redirect Example:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>JSP Redirect Example</title>
</head>
<body>
 <%
  String site = "https://www.dineshonjava.com" ;
  response.setStatus(response.SC_MOVED_TEMPORARILY);
  response.setHeader("Location", site);
  response.sendRedirect(site);
  
 %>
</body>
</html> 

When the above JSP run on the server, it redirects to www.dineshonjava.com. If you notice the URL bar, it is changed to www.dineshonjava.com

It is a 2 step process:
Step 1: JSP Container receives the request for current JSP. It compiles and run the JSP. During execution, it finds the redirect for new resource.

Step 2: It redirects to the new resource.

During these 2 steps, URL is changed as it is considered as a completely new request.

JSP Redirect is slower than JSP forward where JSP container internally forwards the request to new resource and URL remains intact, hence user does not know about request forwarding.

Now let us put above code in index.jsp and call this JSP using URL http://localhost:8080/index/index.jsp. This would take you given URL https://www.dineshonjava.com.

 

<<Previous <<   || Index ||   >>Next >>
Previous
Next