Saturday, August 6, 2016

Write a program to store the user information into Cookies. Write another program to display the above stored information by retrieving from Cookies.

Aim:Write a program to store the user information into Cookies. Write another program to display the above stored information by retrieving from Cookies.


Program:

AddCookieServlet.html:

<html>
<body>
<center>
<form name="Form1"
method="post"
action="ACS">
<B>Enter a value for MyCookie:</B>
<input type=textbox name = "d1" size=25 value="">
<input type=textbox name = "d2" size=25 value="">
<input type=textbox name = "d3" size=25 value="">
<input type=submit value = "Submit">
</form>
</body>
</html>


AddCookieServlet.java


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AddCookieServlet extends HttpServlet 
{
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException 
{
// Get parameter from HTTP request.
String a = request.getParameter("d1");
String b = request.getParameter("d2");
String c = request.getParameter("d3");

// Create cookie.
Cookie cookie1 = new Cookie("MyCookie1", a);
Cookie cookie2 = new Cookie("MyCookie2", b);
Cookie cookie3 = new Cookie("MyCookie3", c);
// Add cookie to HTTP response.
response.addCookie(cookie1);
response.addCookie(cookie2);
response.addCookie(cookie3);
// Write output to browser.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>MyCookie has been set to");
pw.println(a+"   "+b+"   "+c);
pw.close();
}
}

GetCookieServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetCookiesServlet extends HttpServlet 
{
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException 
{
// Get cookies from header of HTTP request.
Cookie[] cookies = request.getCookies();
// Display these cookies.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>");
for(int i = 0; i < cookies.length; i++)
 {
String name = cookies[i].getName();
String value = cookies[i].getValue();
pw.println("name = " + name +
"; value = " + value);
}
pw.close();
}
}

Output:









Type http://localhost:9999/servlets/GCS to retrive cookies information







Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home