cookie是隻要你再客戶端(瀏覽器)那的cookie開放而且有數據,每一次請求的時候都會自動添加到HTTP請求報文中。而後後臺能夠實時接收觀察獲取這些cookiejava
jsjquery
<body> <div> <input id="inVal" type="text" /><button id="btn">發送</button> </div> <script src="../js/lib/jquery-3.2.1.js"></script> <script> $('#btn').click(function () { checkCookie(); }); function setCookie(cname,cvalue,exdays){ var d = new Date(); d.setTime(d.getTime()+(exdays*24*60*60*1000)); var expires = "expires="+d.toGMTString(); document.cookie = cname+"="+cvalue+"; "+expires; } function getCookie(cname){ var name = cname + "="; var ca = document.cookie.split(';'); for(var i=0; i<ca.length; i++) { var c = ca[i].trim(); if (c.indexOf(name)==0) { return c.substring(name.length,c.length); } } return ""; } function checkCookie(){ var user=getCookie("username"); if (user!=""){ alert("歡迎 " + user + " 再次訪問"); $.ajax({ url: "postTest.do?", type: "POST", dataType: "text", contentType:"application/text;charset=UTF-8", data: {"key1":"val1","key2":"val2"}, success: function(data) { alert(data); }, error: function() { alert("請求出錯!"); } }); } else { user = prompt("請輸入你的名字:",""); if (user!="" && user!=null){ setCookie("username",user,30); } } } </script> </body>
javaweb
package com.any.demoSpring.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.net.URLDecoder; @Controller public class TestController { @RequestMapping(value="postTest.do",method= RequestMethod.POST,produces = "application/text;charset=UTF-8;") @ResponseBody public String postTest(HttpServletRequest request, HttpServletResponse response) throws IOException { Cookie[] cookies = request.getCookies(); System.out.println("Cookie長度:" + cookies.length); //讀取本機共存在多少COOKIE if (cookies != null) { for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals("username")) { System.out.println("cookie:username=" + URLDecoder.decode(cookies[i].getValue(),"UTF-8")); } } } else { System.out.println("沒有任何Cookie"); } //建立一個cookie Cookie cookie = new Cookie("key1", "cookieValue1"); cookie.setPath("/");// 這個要設置 // cookie.setDomain(".zhangsan.com");//這樣設置,能實現兩個網站共用 cookie.setMaxAge(365 * 24 * 60 * 60);// 不設置的話,則cookies不寫入硬盤,而是寫在內存,只在當前頁面有用,以秒爲單位,關閉瀏覽器就沒了 response.addCookie(cookie); //添加cookie到響應對象中 //建立第二個cookie cookie = new Cookie("key2", "cookieValue2"); cookie.setPath("/"); cookie.setMaxAge(365 * 24 * 60 * 60); response.addCookie(cookie); //添加cookie到響應對象中 //刪除一個cookie:添加第三個Cookie 用這個cookie來毀掉以前的那個cookie 達到刪除的效果! cookie = new Cookie("username","");//這邊得用"",不能用null cookie.setPath("/");//設置成跟寫入cookies同樣的 cookie.setMaxAge(0); response.addCookie(cookie); return "來自後臺的數據!"; } }