Search This Blog

Saturday, 15 September 2012

Practical 24) Develop an application to demonstrate how the client (browser) can remember the last time it visited a page and displays the duration of time since its last visit. (Hint: use Cookie).


Filename-UserVisited.java

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

public class UserVisited extends HttpServlet
{
          public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException
          {
                   res.setContentType("text/html");
                   PrintWriter out = res.getWriter();
                  
                   Date d = new Date();
                  
                   String myDateStr = String.valueOf(d.getTime());
                  
                   Cookie myc = new Cookie("Pranav",myDateStr);
                   myc.setMaxAge(60*60*24*365);
                   res.addCookie(myc);
                  
                  
                   Cookie cary[] = req.getCookies();
                  
                   if(cary != null)
                   {
                             for(int i=0; i<cary.length; i++)
                             {
                                      if(cary[i].getName().equals("Pranav"))
                                      {
                                                long t1 = Long.parseLong(cary[i].getValue());
                                                long t2 = d.getTime();
                                                long t = t2 - t1;
                                                out.println("You visited last date " + new Date(t1) + "<br>Current Date is " + new Date(t2) + "  " );
                                                out.println("<br>You have visited since " + (t/1000) + " Seconds");
                                      }
                             }
                   }
                  
                            
          }
         
          public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException
          {
                   doPost(req,res);
          }
}

1 comment: