Cookie is a small piece of data that can be embedded in the HTTP request and response, which is generated on the server and returns the user as part of the response header. After the browser receives the response containing the cookie, the browser is written in the form of the "Keyword / Value" pair in the form of a client to store the cookie. The browser will send cookies and subsequent requests to the same server, and the server can read the cookie in the cookie to set the validity period, and the expiration cookie will not be sent to the server.
The Servlet API provides a cookie class that encapsulates some operations for cookies. Servlet can create a new cookie, set its keywords, values, and validity periods, and then set the cookie to send back the browser in the HTTPSERVLETRESPONSE object, and get cookies from the HTTPServletRequest object.
Programming: Cookie is widely used in the actual servlet program, which is an example of getting a cookie information from a servlet.
The source code of ShowCookies.java is as follows:
import javax.servlet *;. import javax.servlet.http *;. / ***
This is a simple servlet that 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 = Resp.Getwriter (); // Get an Array Containing All of the cookies cookie cookies [] = req.getCookies (); // Write the page header out.println (""); Out.println ("
"); out.println ("Name < / TH> | Value th> " " | Comment th> | Max Age TH> Tr> "); for (int i = 0; i " c.getname () " td> | " c.getValue () "< |
转载请注明原文地址:https://www.9cbs.com/read-99097.html New Post(0)
|
---|