JSP - Page Redirecting

In this article, we will discuss page redirecting with JSP. Page redirection is generally used when a document moves to a new location and we need to send the client to this new location. This can be because of load balancing, or for simple randomization.
The simplest way of redirecting a request to another page is by using sendRedirect() method of the response object. Following is the signature of this method −
public void response.sendRedirect(String location) throws IOException 
Here response is an implicit object that will receive the generated HTML output. response implicit object is an instance of HttpServletResponse class.

Page Redirecting in JSP Page Example

Let's create two JSP pages - page1.jsp and page2.jsp.
Now we will write a code to redirect from page1 to page2.

page1.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
 <h1> Inside Page 1 </h1>
 
 <%

        String redirectURL = "http://localhost:8080/jsp-tutorial/redirect/page2.jsp";

        response.sendRedirect(redirectURL);

    %>
 
</body>
</html>

page2.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
 <h1>Inside page 2</h1>
</body>
</html>
When you hit http://localhost:8080/jsp-tutorial/redirect/page1.jsp link ina browser will navigate to http://localhost:8080/jsp-tutorial/redirect/page2.jsp link with below screen:
In the next article, we will learn how to use JDBC in JSP with an example.

Comments