A Cookie is a small piece of data that can be embedded in an HTTP request and response and is generated on the server and returned to the user as part of the response header domain. When the browser receives a response that contains a cookie, it writes the contents of the cookie as a "keyword/value" pair to a client-specific text file that stores cookies. The browser sends the cookie and subsequent requests to the same server, and the server can read the cookie again in a valid period setting, and the expired cookie is not sent to the server.
The Servlet API provides a cookie class that encapsulates some of the operations on cookies. The Servlet can create a new cookie, set its keywords, values, and expiration attributes, and then send the cookie settings back to the browser in the HttpServletResponse object, as well as from the HttpServletRequest object to get the cookie.
Programming idea: Cookies are widely used in real-world servlet programming, and here's an example of getting cookie information from a servlet.
Showcookies.java's source code is as follows:
Import javax.servlet.*;
Import javax.servlet.http.*;
/**
* <p> This is a simple servlet, displays all of the
* Cookies present in the request
*/
public class Showcookies extends HttpServlet
{
public void Doget (HttpServletRequest req, HttpServletResponse resp)
Throws Servletexception, Java.io.IOException
{
Set the content type of the response
Resp.setcontenttype ("text/html;charset=gb2312");
Get the PrintWriter to write the response
Java.io.PrintWriter out = Resp.getwriter ();
Get a array containing all of the cookies
Cookie cookies[] = req.getcookies ();
Write the page header
Out.println ("Out.println ("Out.println ("<title> Servlet Cookie Information </title>");
Out.println ("Out.println ("<body>");
if ((cookies = null) | | (cookies.length = 0)) {
Out.println ("No cookies");
}
else {
Out.println ("<center> cookie information in response message");
Display a table with all of the info
Out.println ("<table border>");
Out.println ("<tr> <th> Name </th> <th> Value </th>" +
"<th> Comment </th> <th> Max age </th> </tr>");
for (int i = 0; I cookies.length i++) {
Cookie C = cookies[i];
Out.println ("<tr> <td>" +c.getname () + "</td> <td>" +
C.getvalue () + "</td> <td>" +c.getcomment () + "</td> <td>" +
C.getmaxage () + "</td> </tr>");
}
Out.println ("</table> </center>");
}
Wrap up
Out.println ("</body>");
Out.println ("Out.flush ();
}
/**
* <p> Initialize the servlet. This is called once when the
* The servlet is loaded. It is guaranteed to complete before any
* Requests are made to the servlet
* @param cfg Servlet configuration information
*/
public void init (ServletConfig cfg)
Throws Servletexception
{
Super.init (CFG);
}
/**
* <p> Destroy the servlet. This are called once when the servlet
* is unloaded.
*/
public void Destroy ()
{
Super.destroy ();
}
}