Cookie for Session Management Example

Example:

Required Files:
1. index.html
2. FirstServlet.java
3. SecondServlet.java
4. web.xml

http_session

Index.html

<form action="FirstServlet.java">
  Name:<input type="text" name="uname"/><br/>
</form>

FirstServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet1 extends HttpServlet {
   public void doGet(HttpServletRequest request, HttpServletResponse response){
     try{
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();

      String name = request.getParameter("uname");
      out.print("Hello "+name);

      Cookie ck=new Cookie("uname",s1);
      response.addCookie(ck);

      out.print("< form action='SecondServlet' >");
      out.print("<input type='submit' value='ok'>");
      out.print("<form >");
      out.close();
    }catch(Exception exp){
       System.out.println(exp);
     }
  }
}

SecondServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet2 extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response){
  try{
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      Cookie[] c=request.getCookies();
      out.print("Hiii"+" "+c[0].getValue());
  }catch(Exception exp){
      System.out.println(exp);
   }
  }

}

http_session
http_session
http_session

Our Services:

Java Training | Python Training | Machine Learning with Python Training | Deep Learning with Python Training | Projects

SILAN Technology
Call to: 9439202111  |  9658317757  |  0674-2361252

Comment