获取cookie的3种方式

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/LearningForFun/article/details/64921635

创建Cookie

//使用URLEncoder.encode()编码,因为cookie不能存储中文,否则有中文会报错
String city = URLEncoder.encode("北京_BJ", "utf-8");
//创建Cookie
Cookie cookie = new Cookie("city", city);
//设置Cookie的最大生命周期,否则浏览器关闭后Cookie即失效
cookie.setMaxAge(Integer.MAX_VALUE);
//将Cookie加到response中
response.addCookie(cookie);

获取Cookie的3种方式:

JSP表达式

在jsp页面中遍历cookie,找到指定的cookie

<%
    String city = "";
    //获取所有Cookie
    Cookie[] cookies = request.getCookies();
    //如果浏览器中存在Cookie
    if (cookies != null && cookies.length > 0) {
        //遍历所有Cookie
        for(Cookie cookie: cookies) {
            //找到name为city的Cookie
            if (cookie.getName().equals("city")) {
                //使用URLDecode.decode()解码,防止中文乱码
                city = URLDecoder.decode(cookie.getValue(), "utf-8");
            }
        }
    }
%>

在需要显示的位置用jsp表达式展示

<%= city %>

EL内置对象cookie

使用 ${cookie.city.value } 直接获得即可,但如果有中文的话,会出现中文乱码

${cookie.city.value }

使用jQuery,需引入js文件:
jquery-3.2.0.jsjquery-3.2.0.min.js 官网下载链接

<script src="js/jquery-3.2.0.js"></script>

使用jQuery Cookie插件,需引入js文件: jquery.cookie.js 官网下载链接

<script src="js/jquery.cookie.js"></script>

将Cookie存的内容放到id=”city”的元素中

<script type="text/javascript">
$(document).ready(function() {
    //$.cookie("city") 获取name为city的Cookie的值
    //$("#city").val(str) 设置id="city"的元素的值为str
    $("#city").val($.cookie("city"));
});
</script>
<input type="text" id="city">

测试结果

测试结果

测试代码

testCookie.jsp

<%@page import="java.net.URLDecoder"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>testCookie</title>
<script src="js/jquery-3.2.0.js"></script>
<script src="js/jquery.cookie.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    //$.cookie("city") 获取name为city的Cookie的值
    //$("#city").val(str) 设置id="city"的元素的值为str
    $("#city").val($.cookie("city"));
});
</script>
<style type="text/css">
    input {
        width:200px;
    }
</style>
</head>
<body>
<%
    String city = "";
    //获取所有Cookie
    Cookie[] cookies = request.getCookies();
    //如果浏览器中存在Cookie
    if (cookies != null && cookies.length > 0) {
        //遍历所有Cookie
        for(Cookie cookie: cookies) {
            //找到name为city的Cookie
            if (cookie.getName().equals("city")) {
                //使用URLDecode.decode()解码,防止中文乱码
                city = URLDecoder.decode(cookie.getValue(), "utf-8");
            }
        }
    }
%>
<form action="TestCookieServlet">
1.JSP表达式:<br>
&nbsp;&nbsp;&nbsp;<input type="text" value="<%=city %>" ><br><br>
2.EL语句:<br>
&nbsp;&nbsp;&nbsp;<input type="text" value="${cookie.city.value }"><br><br>
3.jQuery:<br>
&nbsp;&nbsp;&nbsp;<input type="text" id="city"><br><br>
&nbsp;&nbsp;&nbsp;<input type="submit" value="获取Cookie" ><br>
</form>
</body>
</html>

TestCookieServlet.java

package com.cookie.test;

import java.io.IOException;
import java.net.URLEncoder;

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;

@WebServlet("/TestCookieServlet")
public class TestCookieServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //使用URLEncoder.encode()编码,因为cookie不能存储中文,否则有中文会报错
        String city = URLEncoder.encode("北京_BJ", "utf-8");
        //创建Cookie
        Cookie cookie = new Cookie("city", city);
        //设置Cookie的最大生命周期,否则浏览器关闭后Cookie即失效
        cookie.setMaxAge(Integer.MAX_VALUE);
        //将Cookie加到response中
        response.addCookie(cookie);
        //重定向到jsp页面
        response.sendRedirect("testCookie.jsp");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }
}
展开阅读全文

没有更多推荐了,返回首页