Random Redirector

In this program we are going to make such a servlet which will be responsible to select a site randomly from the list of sites you have entered.

Random Redirector

Random Redirector

     

In this program we are going to make such a servlet which will be responsible to select a site randomly from the list of sites you have entered. Note that the selection of the site will be randomly. 

To make such a servlet firstly make a class named SiteSelectionServlet. Use the Vector class where you can store the sites which you want to select randomly and the other class Random which will helps you to select the site randomly. 

The code of the program is given below:

 

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

public class SiteSelectionInServlet extends HttpServlet {

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

public void init() throws ServletException {
sites.addElement("http://www.roseindia.net");
sites.addElement("http://www.java.sun.com");
sites.addElement("http://www.rediffmail.com");
sites.addElement("http://www.yahoo.com");
sites.addElement("http://www.indiatimes.com");
}

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

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

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

The output of  the program is given below:

Note: The selection will be random.