Cookie使用

package com.zhen.test.o4;

import com.zhen.util.ServletUtilities;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by zhen on 2017-11-14.
 */
public class RepeatVisitor extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        boolean newbie = true;
        Cookie[] cookies = req.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"))){
                    newbie = false;
                    break;
                }
            }
        }
        String title;
        if(newbie) {
            Cookie returnVisitorCookie = new Cookie("repeatVisitor", "yes");
            returnVisitorCookie.setMaxAge(60*60*24*365);// 1 year
            resp.addCookie(returnVisitorCookie);
            title = "Welcome Aboard";
        }else {
            title = "Welcome Back";
        }
        resp.setContentType("text/html");
        PrintWriter out = resp.getWriter();
        out.println(ServletUtilities.headWithTitle(title) + "" +
                "<body bgcolor="#FDF5E6">
" +
                "<h1 align="center">" + title + "</h1>
" +
                "</body></html>");
    }
}


public class ClientAccessCount extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String countString = CookieUtilities.getCookieValue(req, "accessCount", "1");
        int count = 1;
        try{
            count = Integer.parseInt(countString);
        }catch(NumberFormatException nfe){
        }
        LongLivedCookie c = new LongLivedCookie("accessCount", String.valueOf(count + 1));
        resp.addCookie(c);
        resp.setContentType("text/html");
        PrintWriter out = resp.getWriter();
        String title = "Access Count Servlet";
        out.println(ServletUtilities.headWithTitle(title) + "" +
                "<body bgcolor="#FDF5E6">
" +
                "<h1>" + title + "</h1>
" +
                "<h2>This is visit number " + count + " by this browser.</h2>
" +
                "</body></html>");
    }
}


public class RegistrationForm extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        PrintWriter out = resp.getWriter();
        String actionUrl = "/webApp1/servlet/com.zhen.test.o5.RegistrationServlet";
        String firstName = CookieUtilities.getCookieValue(req, "firstName", "");
        String lastName = CookieUtilities.getCookieValue(req, "lastName", "");
        String emailAddress = CookieUtilities.getCookieValue(req, "emailAddress", "");

        String title = "Please Register";
        out.println(ServletUtilities.headWithTitle(title) + "" +
                "<body bgcolor="#FDF5E6">
" +
                "<h1>" + title + "</h1>
" +
                "<form action="" + actionUrl + "">
" +
                "First Name:
" + " <input type="text" name="firstName" value="" + firstName + "">
" +
                "Last Name:
" + " <input type="text" name="lastName" value="" + lastName + "">
" +
                "Email Address:
" + " <input type="text" name="emailAddress" value="" + emailAddress + "">
" +
                "<br/>" + "<input type="submit" value="Register">" +
                "</form></body></html>");
    }
}

public class RegistrationServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        boolean isMissingValue= false;
        String firstName = req.getParameter("firstName");
        if(isMissingValue(firstName)) {
            firstName = "Missing first name";
            isMissingValue = true;
        }
        String lastName = req.getParameter("lastName");
        if(isMissingValue(lastName)){
            lastName = "Missing last name";
            isMissingValue = true;
        }
        String emailAddress = req.getParameter("emailAddress");
        if(isMissingValue(emailAddress)){
            emailAddress = "Missing email address";
            isMissingValue = true;
        }
        Cookie c1 = new LongLivedCookie("firstName", firstName);
        resp.addCookie(c1);
        Cookie c2 = new LongLivedCookie("lastName", lastName);
        resp.addCookie(c2);
        Cookie c3 = new LongLivedCookie("emailAddress", emailAddress);
        resp.addCookie(c3);
        String formAddress = "/webApp1/servlet/com.zhen.test.o5.RegistrationForm";
        if(isMissingValue){
            resp.sendRedirect(formAddress);
        }else{
            PrintWriter out = resp.getWriter();
            String title = "Thanks for Registering";
            out.println(ServletUtilities.headWithTitle(title) + "" +
                    "<body bgcolor="#FDF5E6">
" +
                    "<h1 align="center">" + title + "</h1>
" +
                    "<ul>
" +
                    "<li><b>First Name</b>: " + firstName + "</b></li>" +
                    "<li><b>Last Name</b>: " + lastName + "</b></li>" +
                    "<li><b>Email address:" +  emailAddress + "</b></li>" +
                    "</ul></body></html>");
        }
    }

    private boolean isMissingValue(String param) {
        return ((param == null) || (param.trim().equals("")));
    }
}


public class CookieUtilities {
    public static String getCookieValue(HttpServletRequest request, String cookieName, String defaultValue) {
        Cookie[] cookies = request.getCookies();
        if(cookies != null){
            for(Cookie c : cookies){
                if(c.getName().equals(cookieName)){
                    return c.getValue();
                }
            }
        }
        return defaultValue;
    }

    public static Cookie getCookie(HttpServletRequest request, String cookieName) {
        Cookie[] cookies = request.getCookies();
        if(cookies != null){
            for(Cookie c : cookies){
                if(c.getName().equals(cookieName)){
                    return c;
                }
            }
        }
        return null;
    }
}

  

Cookie
cookie是小段的文本信息,web服务器将它发送到浏览器,之后,在访问同一网站或域时,浏览器又将它原封不动返回。
cookie使用方式:
1、电商会话中标识用户
2、记录用户名和密码
3、定制站点
4、定向广告
cookie存在的问题:
cookie并不构成严重的安全威胁。cookie不会以任何方式得到解释或执行。浏览器一般对每个站点只接受20个cookie,总共不超过300个,浏览器可以将每个cookie限制在4k,因此不能用来填充硬盘或dos攻击。
cookie可能对隐私造成威胁
删除cookie:
浏览器删除
cookie的发送和接收:
发送到客户程序:
1、创建对象
cookie的key和value都不能包含:[]()=,"/?@:;
Cookie c = new Cookie("userID", "a1234");
2、设置时效
c.setMaxAge(60*60*24*7);// One week
将最大时效设置为0是删除该cookie
3、将cookie放到Http响应报头
response.addCookie(c);
从客户端读取cookie:
1、request.getCookies得到cookie对象组
2、对数据进行循环,调用cookie的getName方法找到cookie,使用它的value
使用cookie属性:
将cookie加到输出报头之前,可以使用setXXX方法设置cookie的各项特征。
尽管每个setXXX都有一个对应的getXXX来取出属性的值,但是,属性是服务器发送到浏览器报头的一部分,但它们不属于由浏览器返回给服务器的报头。
方法:
public void setComment(String comment)
public String getComment()设置和读取cookie注释

public void setDomain(String domainPattern)
public String getDomain()设置和读取cookie适用的域

public void setMaxAge(int lifetime)
public int getMaxAge()规定cookie多长时间后过期,负值(默认值)表示cookie仅仅用于当前浏览会话(用户退出浏览器为止)

public String getName()

public void setPath(String path) 设置获取cookie所适用的路径。如果没有指定一个路径,浏览器只将该cookie返回给发送cookie所在目录之下的URL

public void setSecure(boolean secureFlag)
public boolean getSecure()
设置或取的响应的boolean值,表示cookie是否只能通过加密链接(SSL)发送。默认是false

public void setValue()
public String getValue()

public void setVersion(int version)
public int getVersion()

修改cookie的值:
替换cookie之前的值,需要发送相同的cookie名称,但要使用不同的cookie值。需要重新应用cookie的所有的相关属性,response.addCookie(c)
删除cookie,只需要使用setMaxAge将它最大时效设置为0

使用例子:

原文地址:https://www.cnblogs.com/aigeileshei/p/7834394.html