Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Servlet – Page Redirection

  • Last Updated : 30 Dec, 2021

Programming for a website is an art. To provide the view in an eminent manner, numerous steps are getting taken. Usually, a client(A simple JSP page) provides a request to a web server or app server and they process the request and provide the response. Sometimes, it happens that in order to load balance the server, a few pages might be moved to other places, or according to the authorized authenticated credentials, the response should get diverted. In this article, let us see how to handle those scenarios. i.e. Using page redirection can be achieved via servlets.

sendRedirect(): It redirects the response to another resource that is present inside the server or even outside. Hence it makes the client(browser) create a new request and hence we can see the new URL in the browser. sendRedirect() can accept a relative URL and hence only redirection can happen inside or outside the server.

Proper syntax to do page redirection is

public void sendRedirect(String URL)throws IOException;  

Let us see an example of how to do that. Here let us do a user is searching a key term and on click of the button, it will get redirected to the GeelsforGeeks page.

Example

JSP Code: index.jsp

<%@ 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>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Learn Courses Online</title>
</head>
<body>
    <h1>Example to show page redirection!</h1>
    <form action="searchServlet" method="post"><!-- It is calling searchServlet on click of button -->
        Enter your search term: <input type="text" name="yourSearchTerm" size="20">
        <input type="submit" value="Invoke Search" />
    </form>
</body>
</html>

Java code: (Servlet code) -> SearchServlet.java

Java




import java.io.IOException;
  
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
  
// Servlet implementation class SearchServlet
@WebServlet("/searchServlet")
public class SearchServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
         
    public SearchServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    // @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
  
          // set response content type
          response.setContentType("text/html");
  
          // New location to be redirected, it is an example
          String site = new String("https://www.geeksforgeeks.org/learn-java-on-your-own-in-20-days-free/");
            
          // We have different response status types. 
          // It is an optional also. Here it is a valid site
          // and hence it comes with response.SC_ACCEPTED
          response.setStatus(response.SC_ACCEPTED);
          response.setHeader("Location", site); 
          response.sendRedirect(site);
          return;
    }
  
}

The above set of lines should be present in a dynamic web project pattern and once it is created in eclipse, by default it will come with the web.xml file

XML




<?xml version="1.0" encoding="UTF-8"?>
    <display-name>sampleProject1</display-name>
    <!-- We are using only index.jsp. in some cases if we want to 
         specify other welcome files, they need 
         to be listed here, hence shown here -->
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
</web-app>

Once the index.jsp page is run on the server (Usually Apache Tomcat) will be used, we can see the following output. A short video will explain how it is getting done

By using request.getRequestDispathcer(“<a specific page present in the same webserver>”).forward(request, response) we can do page redirect. But the specified page should be available in the webserver that is getting used. Otherwise, it cannot forward/redirect. As a thumb rule, if the requirement is redirecting to pages which is present outside the server, then go for the response.sendRedirect. The name itself specifies that it is always a new request and can be used within or outside of the server. The main thing is it works on the client-side. Regarding HttpResponse.setStatus, we have different status set

Status code explanation

Let us see how the page redirection works out with “getRequestDispatcher().forward”. Servlet code alone will have a change and also since the forwarded page should be available in the same web server, it is also shown here.

Java




import java.io.IOException;
  
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
  
@WebServlet("/searchServlet")
public class SearchServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
         
    public SearchServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
  
    // @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
  
          // searchpage.jsp should be available in 
          // the mentioned webserver, then below code works fine  
          request.getRequestDispatcher("searchpage.jsp").forward(request, response);
          return;
    }
  
}

searchpage.jsp

<%@ 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>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Learn Courses Online</title>
</head>
<body>
    <h1>Example to show page redirection via forward!</h1>
    <a href = "https://www.geeksforgeeks.org/learn-java-on-your-own-in-20-days-free/">Learn Java</a>
</body>
</html>

Output is explained in the attached video

Conclusion

Hence by using response.sendRedirection(“<a valid URL>”) which can be either present in the same webserver/outside and request.getRequestDispatcher(“<a valid page present in the same webserver>”).forward(request, response) we can do page redirection. Due to several reasons, it can be done. The ultimate concept is the end-user is provided with a proper response page.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!