Saturday, June 4, 2011

How to Redirect Servlet Call to Another URL

To redirect a call from a servlet to some other url, use the sendRedirect() method of the HttpServletResponse object that is passed to the service() method. The sendRedirect() method takes the new destination url as a string parameter.

package org.best.example;

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

public class ExampleServlet extends HttpServlet {
  
    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */

    protected void service(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

        //Redirect call to another url
        response.sendRedirect("http://www.java.com");
    }
  
}

No comments: