Servlet - Page Redirection
Last Updated :
04 Jan, 2023
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 GeeksforGeeks 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"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<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.
Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Java Programs - Java Programming Examples In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read