Java Servlet Programing Laungage

Java Servlet Projects

Servlet Project 3

adplus-dvertising
Java Servlet :Example of Random Redirector
Previous Home Next

This example shows you how to select the random url  by using the JDBC and the servlet.

index.html

<html>
	<head>
     <title>My Random Site selection application</title>
	</head>
	<body>
	 <a href="randomselection">click here to see the result</a>
	</body>
</html>

web.xml

<web-app>
	<servlet>
	 <servlet-name>s1</servlet-name>
	 <servlet-class>RandomSelection</servlet-class>
	</servlet>
	<servlet-mapping>
	 <servlet-name>s1</servlet-name>
	 <url-pattern>randomselection</url-pattern>
	</servlet-mapping>
</web-app>

RandomSelection.java

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class RandomSelection extends HttpServlet {
	Random random = new Random();
	Vector s1 = new Vector();
	public void init() throws ServletException {
	s1.addElement("http://www.r4r.co.in");
	s1.addElement("http://www.facebook.com");
	s1.addElement("http://www.santabanta.com");
	s1.addElement("http://www.r4rtechsoft.com");
	s1.addElement("http://www.yahoo.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()) % s1.size();
	String s = (String)s1.elementAt(siteIndex);
	response.setStatus(response.SC_MOVED_TEMPORARILY);
	response.setHeader("Location", s);
	}
}
Previous Home Next