how to send redirect from java servlet

www.igift‮edi‬a.com

To send a redirect response from a Java servlet, you can use the sendRedirect() method of the HttpServletResponse object.

Here is an example code snippet that demonstrates how to use the sendRedirect() method to redirect the client to a different URL:

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyServlet extends HttpServlet {

  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String newUrl = "https://www.example.com/new-page";
    response.sendRedirect(newUrl);
  }
}

In this example, the doGet() method of the servlet gets the HttpServletResponse object and calls the sendRedirect() method with the new URL as a parameter. When the client receives this response, it will automatically make a new request to the specified URL.

You can also use a relative URL instead of an absolute URL in the sendRedirect() method. For example:

response.sendRedirect("new-page");

In this case, the client will be redirected to a page relative to the current page.

It is important to note that once the sendRedirect() method is called, no further processing of the response is allowed. Therefore, you should make sure to call it only when you do not need to perform any further processing of the response.