Page Redirection in Servlet

As of now, we have discussed Session in Servlet. In this article, we will discuss Page Redirection in Servlet and we will see an Example showing Page Redirection.

What is Page Redirection?

Sometimes we request for some page the server takes us to another page so the techniques where the client is sent to a new location other than the requested location is Page Redirection.

  • This is done using the sendRedirect() method in servlet.
  • sendRedirect() is a method of HttpServletResponse.

Syntax for sendRedirect()

public void sendRedirect(String URL)throws IOException;

Example:

response.sendRedirect("http://www.codedec.com");

We can use sendStatus() and setHeader() to sends back the response to browser.

String abc="http://www.codedec.com"
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("location",abc);

Let’s see an Example for Page Redirection in Servlet

In this example, we will see Page Redirection Example.

PageServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.setContentType("text/html");
    String abc=new String("http://www.codedec.com");
    response.setStatus(response.SC_MOVED_TEMPORARILY);
    response.setHeader("location", abc);
  }

web.xml

<servlet>
    <servlet-name>PageServlet</servlet-name>
    <servlet-class>PageServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>PageServlet</servlet-name>
    <url-pattern>/PageServlet</url-pattern>
</servlet-mapping>

Output

When we run this Program it will redirect us to https://codedec.com/ site.

In the next article, we shall see The Input and Output Streams in Servlet i.e Servlet InputOutput Stream.