postheadericon 14. Write a Servlet which displays a message and also displays how many times the message has been displayed (how many times the page has been visited).

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

@WebServlet("/PageVisitCounter")

public class PageVisitCounter extends HttpServlet
{
    public void doGet(HttpServletRequest req , HttpServletResponse res) 
	throws IOException , ServletException
    {
        PrintWriter out = res.getWriter();
		Cookie[] myCookie = req.getCookies();
		boolean found = false;
		int v=0;
        if(myCookie != null)
        {
			for(int i=0; i<myCookie.length;i++)
			{
				if(myCookie[i].getName().equals("pageCount"))
				{     
					v = Integer.parseInt(myCookie[i].getValue());
					v++;     
					Cookie c1 = new Cookie("pageCount",String.valueOf(v));
					res.addCookie(c1);
					out.println("Visit No.:"+v);
					found = true;
					break;
				}				 
			}           
        }
		if(found==false)
		{
			Cookie c1 = new Cookie("pageCount",String.valueOf(v));
            res.addCookie(c1);
            out.println("<h1>Welcome to www.BipinRupadiya.com site</h1><br><br><br>You have done first visit..!");
		}      
    }	
}
NOTE :  Enable Cookie in your browser to run this example.

Follow by Email

Blog Archive

Total Pageviews

© BipinRupadiya.com. Powered by Blogger.