Cookie:客户端会话技术,将数据保存到客户端,以后每次请求都携带Cookie数据进行访问
1:创建Cookie对象,设置数据
Cookie cookie=new Cookie("key","value");
2发送Cookie到客户端:使用Response对象
response.addCookie(cookie)
- package com.chen.web;
-
- 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;
- import java.io.IOException;
-
- @WebServlet("/a1")
- public class Servlet1 extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- //创建cookie对象
- Cookie cookie = new Cookie("username","aaa");
- //发送cookie 使用response对象
- resp.addCookie(cookie);
- }
- }
1:获取客户端携带的所有Cookie,使用request对象
Cookie[] cookies = req.getCookies();
2:遍历,通过getName() ,getValue()拿数据
- package com.chen.web;
-
- 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;
- import java.io.IOException;
-
- @WebServlet("/a2")
- public class Servlet2 extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- //获取客户端携带的所有Cookie:使用request对象
- Cookie[] cookies = req.getCookies();
- //遍历数组,获取Cookie
- //getName获取名称 getValue获取值
- for (Cookie cookie : cookies) {
- String name = cookie.getName();
- if("username".equals(name)){
- String value = cookie.getValue();
- System.out.println(name+":"+value);
- break;
- }
-
-
- }
-
- }
- }
然后启动tomcat,分别先访问,a1Servlet,在访问a2Servlet,如果控制台输出了,那就说明代码正确了
默认情况下下,Cookie存储在浏览器内存中,当浏览器关闭,内存释放,责Cookie被销毁
setMaxAge(int second) 设置Cookie 存活时间
整数:将Cookie写入浏览器所在的硬盘下,持久化存储,到时见自动删除
负数:默认值,Cookie在当前浏览器内存中,当浏览器被关闭,Cookie被销毁
零:删除对应的Cookie
例如设置存活一周
cookie.setMaxAge(60*60*24*7);//设置Cookie存活一周
需要进行转码:使用URL编码
编码发送:URLEncoder.encode("",字符集)
- String value="牛马";
- value = URLEncoder.encode(value, "UTF-8");
- Cookie cookie = new Cookie("username",value);
解码使用:URLDecoder.decode(" ",字符集)
- String value = cookie.getValue();
- value= URLDecoder.decode(value,"UTF-8");