SERVLET TO IMPLEMENT COOKIES

index.html

<html>
<body>
<form action="servlet1" method="post"> 
Name:<input type="text" name="userName"/><br/> 
<input type="submit" value="Go"/> 
</form> 
</body>

</html>

FirstServlet,java

import java.io.*; 
import javax.servlet.*; 
import javax.servlet.http.*; 
 
  public class FirstServlet extends HttpServlet { 
  public void doPost(HttpServletRequest request, HttpServletResponse response){ 
    try{ 
 
    response.setContentType("text/html;charset=UTF-8"); 
    PrintWriter out = response.getWriter(); 
 
  Strring n=request.getParameter("userName"); 
    out.print("Welcome "+n); 
 
    Cookie ck=new Cookie("uname",n);   //creating cookie object 
    response.addCookie(ck);                     //adding cookie in the response 
 
    //creating submit button 
 
      out.print("<form action='servlet2'method='post'> "); 
      out.print("<input type='submit' value='Go'>"); 
      out.print("</form>"); 
         
    out.close(); 
 
        }catch(Exception e){System.out.println(e);} 
  } 



SecondServlet.java

import java.io.*; 
import javax.servlet.*; 
import javax.servlet.http.*; 
 
public class SecondServlet extends HttpServlet { 
 
public void doPost(HttpServletRequest request, HttpServletResponse response){ 
    try{ 
 
    response.setContentType("text/html;charset=UTF-8"); 
    PrintWriter out = response.getWriter(); 
    out.print("<h1>");
     
    Cookie ck[]=request.getCookies(); 
    out.print("Hello "+ck[0].getValue()); 
    out.print("</h1>");
 
    out.close(); 
 
         }catch(Exception e){System.out.println(e);} 
    } 


web.xml

<web-app> 
 
<servlet> 
<servlet-name>FirstServlet</servlet-name> 
<servlet-class>FirstServlet</servlet-class> 
</servlet> 
 
<servlet-mapping> 
<servlet-name>FirstServlet</servlet-name> 
<url-pattern>/servlet1</url-pattern> 
</servlet-mapping> 
 
<servlet> 
<servlet-name>SecondServlet</servlet-name> 
<servlet-class>SecondServlet</servlet-class> 
</servlet> 
 
<servlet-mapping> 
<servlet-name>SecondServlet</servlet-name> 
<url-pattern>/servlet2</url-pattern> 
</servlet-mapping> 
 
</web-app> 

OUTPUT




No comments:

Post a Comment