This section contains the details about the Retrieving data from Cookie.
Retrieving data from Cookie
Cookies can only be read by the application server that had written them in the client browser. Cookies can be used by the server to find out the computer name, IP address or any other details of the client computer by retrieving the remote host address of the client where the cookies are stored.
The HttpServletRequest class provides the getCookies() method that returns an
array of cookies that the request object contains.
Example :
This example retrieve the cookie value set in the previous example. In the given code, we use the getCookies() method that returns an array of cookies that the request object contains. We use this array to find our desired value by checking each value through loop . Given below the sample code :
package devmanuals; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class GetCookie extends HttpServlet { PrintWriter pw = null; public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doPost(req, res); } public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { pw = res.getWriter(); String username = null; // Retrieve the cookies, if any, stored in the client browser Cookie ck[] = req.getCookies(); if (ck != null) { for (int i = 0; i < ck.length; i++) { if (ck[i].getName().equals("user")) // Retrieve username from the cookie username = ck[i].getValue(); } res.setContentType("text/html"); pw.println(" Hello! " + username); } else { pw.println("No cookies found"); } } }
Output :
After executing code you will get the username stored in the cookie's name attribute "user" :
[ 0 ] Comments