sendRedirect() Method

sendRedirect() is a such type of method which redirects the response to another resource. This method makes the client(browser) to create a new request to get to the resource. The client can see the new url in the browser. sendRedirect() accepts relative URL, so it can go for resources inside or outside the server.

The main difference between a redirect and a request dispatching is that, redirect method makes the client(browser) create a new request to get to the resource, the user can see the new URL while request dispatching get the resource in same request and URL does not changes. Also, another very important difference is that, sendRedirect() works on response object while request dispatch work on request object.

Let's see a demo program:

When to use sendRedirect() method?

  • When a Programmer want to sent the client request to another Web site on a different server.
  • To redirect the errors to another resource (like Servlet or JSP).
  • To send any HTML form existing on the server to client.

MyServletDemo.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServletDemo extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(“text/html”);
PrintWriter pw = response.getWriter();
try {
response.sendRedirect("http://www.java8s.com");
}finally {
pw.close();
}
}
}

Our Services:

Java Training | Python Training | Machine Learning with Python Training | Deep Learning with Python Training | Data Science with Python Training | Projects

SILAN Technology, BBSR
Call to: 9439202111  |  9658317757  |  0674-2361252

Comment