In this section we will discuss how a page can be redirected randomly.
Redirect The Page Randomly
In this section we will discuss how a page can be redirected randomly.
To solve the above task I used the random method of the class Math. This method generates +ve double value number greater than or equal to 0.0 and less than 1.0. In the example at first I created a list of pages which I have to redirected further set the status and header of the redirected page.
Example :
RandomRedirectServlet.java
import java.io.IOException; import java.io.PrintWriter; import java.util.*; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class RandomRedirectServlet extends HttpServlet { List l= new ArrayList(); public void init() { l.add("http://www.Devmanuals.com"); l.add("http://www.facebook.com"); l.add("http://www.Google.com"); l.add("http://www.rediffmail.com"); l.add("http://www.gmail.com"); } public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { res.setContentType("text/html"); Random rndm = new Random(); int listIndex = ((int)(Math.random()*l.size())); String site = (String)l.get(listIndex); res.setStatus(res.SC_MOVED_TEMPORARILY); res.setHeader("Location", site); } }
web.xml
<web-app> <display-name>SendRedirectExample</display-name> <servlet> <servlet-name>RandomRedirectServlet</servlet-name> <servlet-class>RandomRedirectServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>RandomRedirectServlet</servlet-name> <url-pattern>/RandomRedirectServlet</url-pattern> </servlet-mapping> </web-app>
Output :
When you will execute this example you will get that every time a new web page is opened which are listed in the above example.
[ 0 ] Comments