Redirect to another page in jsp

In JSP(JavaServer Pages),you can  redirect to another page using various methods.Here are some ways to achieve this.

Method1: response.sendRedirect()

Explanation:

The ‘sendRedirect()’ method is part of the ‘HttpServletResponse’ object.It sends a response to the client(usually the browser)telling it to make a new request to a different URL.This means the URL in the browser will change to the new URL.

Code Example:
<%@ Page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<% 
   boolean shouldRedirect=True;
   if(shouldRedirect){
   response.sendRedirect("another-page.jsp");
   return;
   }
%>

<!DOCTYPE html>
<html>
<head>
    <title>Original Page</title>
</head>
<body>
    <h1>you will not see this message if redirection is successful.</h1>
</body>
</html>
Expected output:
1.When the JSP is accessed and 'shouldRedirect' is 'true',the browser will be redirected to 'anotherPage.jsp'.

2.The URL in the browser will change to 'anotherPage.jsp'.

3.The content of 'anotherPage.jsp' will be displayed.

 

 Method 2:<jsp:forward>

Explanation:

The ‘<jsp:forward>’ tag is used to forward the request to another resource on the server.This forwarding happens internally on the server,so the browser’s URL remains unchanged.

Code Example:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
   boolean shouldForward=true;
   if(shouldForward)
  {
   request.getRequestDispatcher("anotherPage.jsp").forward(request,response);
   request;
  }
%>
<!DOCTYPE html>
<html>
<head>
   <title>Original Page</title>
</head>
<body>
  <h1>You will not see this message if forwarding is successful.</h1>
</body>
</html>
Expected Output:
1.When the  JSP is accessed  and 'shouldForward' is 'true', the server will forward the request to 'anotherPage.jsp'.

2.The URL in the browser will remain the same.

3.The content of 'anotherPage.jsp' will be displayed.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top