JSP Page Redirect Example

The simplest way of redirecting a request to another page is by using the sendRedirect() method of the response object. 

Following is the signature of this method −
public void response.sendRedirect(String location) throws IOException 
Here the response is an implicit object that will receive the generated HTML output. response implicit object is an instance of the HttpServletResponse class.
All JSP Examples at JSP Source Code Examples.

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:
All JSP Examples at JSP Source Code Examples.


Comments