Servlet Lesson 5: use of cookies, servletcookie

Source: Internet
Author: User

Servlet Lesson 5: use of cookies, servletcookie

Target Planning:

Through this course, we can learn how to use cookies and how to obtain the content in cookies.

Cookie.

1. Cookie is a "key-value" pair stored on the client to identify user information.

2. Cookie Application
-Identify a user in an e-commerce session
-Website Customization
-Targeted advertising
3. Call the Cookie constructor and give the cookie name and cookie value. Both are strings.
Cookie c = new Cookie ("userID", "a1234 ");
4. If you want to tell the browser to store the cookie on the disk, instead of simply saving it in the memory, use setMaxAge (the parameter is in seconds)
C. setMaxAge (60*60*24*7); // One week
5. Put the Cookie into the HTTP Response
Response. addCookie (c );


6. Call request. getCookies to obtain an array consisting of Cookie objects. In this array, call the getName of each object until the desired cookie is found.

7. instance, create cookie

First, create a Cookie:

Core code:

Cookie c = new Cookie("goxuexi", "www.goxuexi.com");c.setMaxAge(60*60*24*7);response.addCookie(c);

All code: TestCookieServlet. java

package com.goxuexi.demo;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * Servlet implementation class TestCookieServlet */@WebServlet("/TestCookieServlet")public class TestCookieServlet extends HttpServlet {private static final long serialVersionUID = 1L;           /**     * @see HttpServlet#HttpServlet()     */    public TestCookieServlet() {        super();        // TODO Auto-generated constructor stub    }/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubCookie c = new Cookie("goxuexi", "www.goxuexi.com");c.setMaxAge(60*60*24*7);response.addCookie(c);}/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubdoGet(request, response);}}

02. Write a code to get the Cookie:


TestCookie. java

Core code:

Cookie[] cs =  request.getCookies();for (Cookie c : cs) {System.out.println(c.getName()+":"+c.getValue());}

All code:

package com.goxuexi.demo;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * Servlet implementation class TestCookie */@WebServlet("/TestCookie")public class TestCookie extends HttpServlet {private static final long serialVersionUID = 1L;           /**     * @see HttpServlet#HttpServlet()     */    public TestCookie() {        super();        // TODO Auto-generated constructor stub    }/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubCookie[] cs =  request.getCookies();               if(cs != null)                for (Cookie c : cs) {System.out.println(c.getName()+":"+c.getValue());}                 }                   }/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubdoGet(request, response);}}

8. instance-use cookies to detect new visitors

// Use cookies to detect the first visitor String result = null; boolean newUser = true; cookie [] cookies = request. getCookies (); if (cookies! = Null) {for (int I = 0; I <cookies. length; I ++) {Cookie c = cookies [I]; if (c. getName (). equals ("repeatVisitor") & (c. getValue (). equals ("yes") {newUser = false; break ;}}if (newUser) {Cookie returnVisitorCookie = new Cookie ("repeatVisitor", "yes"); returnVisitorCookie. setMaxAge (60*60*24*365); response. addCookie (returnVisitorCookie); result = "Welcome Aboard";} else {result = "Welcome Back";} System. out. println (result );




Servlet reads cookie code

Do you want to put objects in cookies? Implement a cookie in the servlet
Cookie c = new Cookie ("cookname ")
Stores objects in cookie type by serialization (objects must be serialized before they can be placed in cookies)
Then, the cookie is saved to the client through the servlet response. addcookie (c. When using
Read Other servlets. This is probably the case.

How does Servlet assign values to cookies?

Do you want to put objects in cookies? Implement a cookie in the servlet
Cookie c = new Cookie ("cookname ")
Stores objects in cookie type by serialization (objects must be serialized before they can be placed in cookies)
Then, the cookie is saved to the client through the servlet response. addcookie (c. When using
Read Other servlets. This is probably the case.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.