Create a servlet that uses Cookies to store the number of times a user has visited servlet.

 Welcome1.html

<html> 

    <head> 

        <title>Cookie Demo</title> 

    </head>  

    <body>  

        <form action="Page1" >      

            Enter Your Name: <input type="text" name="txtName"><br><br> 

            <input type="submit" value=" Click Me ">  

        </form>  

    </body> 

</html> 

Page1.java
package mypack; 
import java.io.IOException; 
import java.io.PrintWriter;  
import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import javax.servlet.http.Cookie; 
public class Page1 extends HttpServlet {  
    public void doGet(HttpServletRequest request, HttpServletResponse response)   
            throws ServletException, IOException {             response.setContentType("text/html;charset=UTF-8");           
PrintWriter out = response.getWriter();                 
out.println("<html><head><title>Page1</title></head>");           
out.println("<body bgcolor=pink >");               
String uname = request.getParameter("txtName");            
out.println("<h1>~~~ Welcome "+uname+" ~~~</h1>");     
        Cookie ck1 = new Cookie("username", uname);              
 Cookie ck2 = new Cookie("visit","1");                  response.addCookie(ck1);          response.addCookie(ck2);           Cookie [] ck = request.getCookies();            for(int i=0;i<ck.length;i++) 
        {           
            if(ck[i].getName().equals("visit")) 
            {        
                int count = Integer.parseInt(ck[i].getValue())+1;                                  
out.println("<h1>Visit No : "+count+"</h1>");                    
ck[i] = new Cookie("visit",count+"");                        
response.addCookie(ck[i]);        
            }              
else 
            { 
                 out.println(ck[i].getName()+ " = "+ck[i].getValue());      
            } 
        } 
        out.println("</body>");                   
out.println("</html>");          
}  





Post a Comment

0 Comments