1.会话
客户端(浏览器)打开后,访问服务器资源,只要客户端服务端不关闭,就可多次请求和响应过程即会话.
分类
1.客户端 Cookie
2.服务端 Session
----------------------------------------------------------------------------------------------------------------------------
一:Cookie
1概念:客户端的会话技术,将数据存储到客户端
注意cookie可以实现一次会话多次响应即打开一次浏览器信息可以共享,若关掉浏览器重开一个则失效
2实现概述
Cookie cookie =new Cookie(name,value):创建Cookie,保存数据到Cookie中
HttpServleResponse中的addCookie():用来将cookie封装到response中响应给浏览器
HttpServleResponse中的getCookie():获取浏览器传递过来的cookie
示例:
//上传cookie
@WebServlet("/ServletCookieDemo1")
public class ServletCookieDemo1 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//1.创建Cookie对象
Cookie cookie = new Cookie("msg","hello");
//2.发送cookie
response.addCookie(cookie);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
}
//访问cookie
@WebServlet("/ServletCookieDemo2")
public class ServletCookieDemo2 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//3.获取cookie
Cookie[] cookies = request.getCookies();
//遍历cookies,获取数据
if (cookies != null){
for (Cookie cookie : cookies) {
//获取名称
String name = cookie.getName();
//获取值
String value = cookie.getValue();
System.out.println(name+":"+value);
}
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
}
案例:
设置cookie时长就可加长cookie的生命周期 |
|