Session management using cookies


Program to demonstrate session management using cookies

 

<!-- Cookie example -->

 

<html>

 

<head>

     <title>Cookies</title>

     <style>

          label

          {

              font-family:vivaldi;

              font-size:x-large;

              letter-spacing:2px;

              line-height:40px;

              font-weight:bold;

          }

     </style>

</head>

 

<body>

     <form method="Post" action="http://localhost:8088/anu/formdata">

         

          <center>

          <h2>Cookies</h2></br>

         

          <label>User Name  </label>

          <input type="text" Name="UN" tabindex=1/>

          </br> </br>

         

          <button type="submit" >Click me!!! </button>

          </center>

             

     </form>

</body>

</html>

 

 

// Cookie Servlet 1 – receives request and sets the cookie in the response

 

import java.io.*; 

import javax.servlet.*; 

import javax.servlet.http.*; 

    

public class CookieServlet1 extends HttpServlet

{   

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException

{ 

     //setting the content type

     res.setContentType("text/html");

 

     //create the stream to write the data 

     PrintWriter pw=res.getWriter();         

 

     // Read username from request object

     String N = req.getParameter("UN"); 

 

     //creating cookie object 

     Cookie C = new Cookie("usr",N);

 

     //adding cookie in the response 

     res.addCookie(C);

    

     //creating response page 

     pw.println("<html><body>");

     pw.println("<center>");

     pw.println("<h2>Welcome to Web Technology</h2>"); 

     pw.println("<form method='Get' action='CookieServlet2'>"); 

     pw.println("<br/><input type='submit' value='Welcome'>"); 

     pw.println("</form>"); 

     pw.println("</center>");

     pw.println("</body></html>");

     pw.close(); 

     } 

}  

 

// Cookie Servlet 2 – reads the cookie and sends a welcome message to the user

 

import java.io.*; 

import javax.servlet.*; 

import javax.servlet.http.*; 

 

public class CookieServlet2 extends HttpServlet

{ 

     public void doGet(HttpServletRequest req, HttpServletResponse res)

throws ServletException, IOException

     { 

          //setting the content type

          res.setContentType("text/html");

 

          //create the stream to write the data 

          PrintWriter pw=res.getWriter();         

 

         Cookie C[]=req.getCookies(); 

    

          pw.println("<html><body>");

          pw.println("<center>");

          pw.println("<h2>Hello "+C[0].getValue()); 

          pw.println("</h2></center>");

         pw.println("</body></html>");

         pw.close(); 

   

    } 

}

 

No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu