June 18, 2011

Redirect request with the sendRedirect() method on HttpServletResponse

The sendRedirect() method on the response object (HttpServletResponse) redirects a request received by the Servlet / web component to another Servlet / web component or URL. The URL may be for a component within the same web application or outside it.

This is in contrast to the RequestDispatcher 's request dispatching that can only internally dispatch a request from one servlet / web component to another one within the same web application.

1) Create a servlet class that contains the re-direction code, in the src folder of the web application

package info.icontraining.servlets;

import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;

public class YahooServlet extends HttpServlet {

   public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    
      res.sendRedirect("http://www.yahoo.com");
   }
}


2) Configure the servlet within the web.xml file present in the WebContent/WEB-INF folder of the web application

<servlet>
   <servlet-name>yahooServlet</servlet-name>
   <servlet-class>info.icontraining.servlets.YahooServlet</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>yahooServlet</servlet-name>
   <url-pattern>/yahoo</url-pattern>
</servlet-mapping>


3) Test the code by typing the following URL in the browser,

http://localhost:8080/WebAppName/yahoo

No comments:

Post a Comment