Home Servlets Random Redirector

Related Tutorials


 
 

Share on Google+Share on Google+

Random Redirector

Advertisement
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

     

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.

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: July 19, 2007

Related Tutorials

Discuss: Random Redirector   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com