Redirect Servlet by Setting Response Location : Redirect « Servlet « Java Tutorial






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

public class MyServlet extends HttpServlet {

  Vector sites = new Vector();
  Random random = new Random();

  public void init() throws ServletException {
    sites.addElement("http://www.java2s.com/Code/Java/CatalogJava.htm");
    sites.addElement("http://www.java2s.com/Tutorial/Java/CatalogJava.htm");
    sites.addElement("http://www.java2s.com/Article/Java/CatalogJava.htm");
    sites.addElement("http://www.java2s.com/Product/Java/CatalogJava.htm");
  }

  public void doGet(HttpServletRequest req, HttpServletResponse res)
                               throws ServletException, IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    int siteIndex = Math.abs(random.nextInt()) % sites.size();
    String site = (String)sites.elementAt(siteIndex);

    res.setStatus(res.SC_MOVED_TEMPORARILY);
    res.setHeader("Location", site);
  }
}
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
    "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>
    <servlet><servlet-name>MyServletName</servlet-name>
             <servlet-class>MyServlet</servlet-class>

             
    </servlet>
    
    <servlet-mapping><servlet-name>MyServletName</servlet-name>
        <url-pattern>/index.html</url-pattern>
    </servlet-mapping>
</web-app>
  Download:  ServletRedirectBySettingResponseLocation.zip( 89 k)








25.15.Redirect
25.15.1.Redirect Servlet by Setting Response Location
25.15.2.Redirect Servlet Based on Path Info And Query String