Tuesday, March 17, 2020

sendRedirect method in Java Servlets

The sendRedirect() method

We can use sendRedirect  method very much like the forward(HttpServletRequest, HttpServletResponse) method from RequestDispatcher interface in Java Servlets. This method can be used to redirect response to another resource like an HTML, Servlet or JSP page. We can provide a relative or absolute URL to this method. This method can also work inside or outside the server as the URL bar of the browser is used to make requests by this method.

sendRedirect method

The other important difference between these two methods is that forward() method sends the same request and response object to the next Servlet, but sendRedirect sends a new request to the next resource every time.


To forward to a new resource with RequestDispatcher interface, we use request.getRequestDispatcher(“NextServlet”).forward(request,response).

To use sendRedirect we use, response.sendRedirect(url)
This method throws IOException like the forward() and the include() methods.

An example of the sendRedirect(url) method in servlet

In this example, we are redirecting the request to the different pages. Notice that the sendRedirect(url) method works at the client-side, that is why we can request anywhere. The requests can be sent within and outside the server.


<!DOCTYPE html>
<meta charset="ISO-8859-1">
<form method="get" action="MyServlet">
<Select name="topic">
<option value="Java">Java</option>
<option value="Pytho">Python</option>
<option value="JavaScript">JavaScript</option>
<option value="Android">Android</option>
<option value="Other">Other</option>
<input type="submit" value="submit">


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;

public class MyServlet extends HttpServlet {
     private static final long serialVersionUID = 1L;
    public MyServlet() {
     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
           String str=request.getParameter("topic");
           else if(str.equalsIgnoreCase("Python"))
           else if(str.equalsIgnoreCase("JavaScript"))
           else if(str.equalsIgnoreCase("Android"))
                response.getWriter().append("<html><body><h2>Some other topics</h2></body></html>");