SiteSelector.java Source code

Java tutorial

Introduction

Here is the source code for SiteSelector.java

Source

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

public class SiteSelector extends HttpServlet {

    Vector<String> sites = new Vector<String>();

    Random random = new Random();

    public void init() throws ServletException {
        sites.addElement("http://www.java2s.com");
        sites.addElement("http://www.servlets.com");
        sites.addElement("http://java.sun.com/products/servlet");
        sites.addElement("http://www.google.com");
    }

    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 = sites.elementAt(siteIndex);

        res.setStatus(res.SC_MOVED_TEMPORARILY);
        res.setHeader("Location", site);
    }
}