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.
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.
Syntax
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.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Welcome</title>
</head>
<body>
<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>
</Select><br>
<input type="submit"
value="submit">
</form>
</body>
</html>
MyServlet.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("/MyServlet")
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public MyServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String str=request.getParameter("topic");
if(str.equalsIgnoreCase("Java"))
{
response.sendRedirect("https://www.programminghunk.com/p/java.html");
}
else if(str.equalsIgnoreCase("Python"))
{
response.sendRedirect("https://www.programminghunk.com/p/python.html");
}
else if(str.equalsIgnoreCase("JavaScript"))
{
response.sendRedirect("https://www.programminghunk.com/p/javascript.html");
}
else if(str.equalsIgnoreCase("Android"))
{
response.sendRedirect("https://www.programminghunk.com/p/android.html");
}
else
{
response.setContentType("text/html");
response.getWriter().append("<html><body><h2>Some
other topics</h2></body></html>");
}
}
}