目录
一、Cookie
二、Session
三、Session和Cookie
一、Cookie
Cookie是一种客户端技术(请求和响应),当用户在浏览器进行登陆等操作时,浏览器会自动保存用户的登录信息存到Cookie内,下次用户打开就无须输入用户名和密码,但这样很危险。
一般保存在本地用户的AppData目录下。
1、在一个网页中cookie是存在上限的。
2、一个web站点可以给浏览器一次传递多个cookie,最多存放20个cookie。
3、一个cookie只能存放一个数据。
4、Cookie的大小不能超过4KB。
5、浏览器上限300个cookie。
1、删除Cookie
1、不设置有效期,关闭浏览器时自动失效;
2、设置有效期时间为 0 ;
2、使用cookie传输中文乱码时
1、其他的数据乱码时也可以使用编码和解码进行处理。
UrlEncoder.encoder(“需要编码的数据”,"编码");
UrlDecoder.decoder(“需要解码的数据”,"编码")
3、Cookie常用的方法
1、Cookie[] cookies = request.getCookies():获取所有的cookie用数组的形式保存。
2、cookie.getValue():获取cookie保存的数据。
3、cookie.getName():获取保存数据进cookie时取的名字。
4、response.addCookie(存取的名称(String),存储的数据(String)):是key=value的模式。
5、cookie.setMaxAge():设置cookie保存的时间。
4、示例
//设置请求的编码(传递过来的数据的编码)
req.setCharacterEncoding("UTF-8");
//设置响应的编码(传给别人时的编码)
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.print("您上一次访问的时间为:");
//获取全部的cookie
Cookie[] cookies = req.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
//设置cookie保存的最大时长
cookie.setMaxAge(60*60);
//cookie.getName():获取key的值(保存时定义的名称)
if ("username".equals(cookie.getName())) {
//cookie.getValue():获取value值(存储的数据)
long time = Long.parseLong(cookie.getValue());
resp.getWriter().print(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(time)));
}
}
} else {
System.out.println("这是您第一次访问!");
}
//response.addCookie(key,value):向Cookie内存储数据,查找时根据key来获取value
resp.addCookie(new Cookie("username",System.currentTimeMillis()+""));
二、Session
Session是一种服务器技术,它可以存储用户独有的数据,将一些中重要的信息存入session放入服务器中,不怎么重要的信息存入Cookie。
1、Session的特点
1、每一个浏览器都会产生一个SessionID,只有当手动关闭浏览器或者退出登录,SessionID才会失效.
2、Cookie中存在Session一个SessionID。
3、用户在登录之后,可以进行其他页面内的访问。
2、session的方法
1、request.getSession():获取Session的对象。
2、session.getID:可以获取Session的ID。
3、session.setAttribute():可以存储数据、对象(key=value)。
4、session.getAttribute():可以获取存储在session中的数据,根据key的名字来获取。
5、session.removeAttribute(“name”):根据key值删除指定的数据。
6、 session.invalidate():注销Session。将Session所有数据清空。
<!--自动失效,设置Session默认的失效时间-->
<session-config>
<!--以分钟为单位,在10分钟后Session自动失效-->
<session-timeout>10</session-timeout>
</session-config>
3、示例
(1)session存入数据和获取ID
public class TestDemo01SessionServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取session对象
HttpSession session = req.getSession();
//往session中存值
session.setAttribute("username","admin");
session.setAttribute("password","12345");
//获取SessionID
resp.getWriter().write(session.getId());
System.out.println("=============getId()=================");
System.out.println("获取sessionID:"+session.getId());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
(2)session获取数据和删除数据
public class TestDemo02SessionServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
//获取存储在session中的值
String username = (String) session.getAttribute("username");
String password = (String) session.getAttribute("password");
PrintWriter out = resp.getWriter();
out.write("username="+session.getAttribute("username"));
out.write("password="+session.getAttribute("password"));
System.out.println("=============getAttribute()===================");
System.out.println("getAttribute()-->username="+session.getAttribute("username"));
System.out.println("getAttribute()-->username="+session.getAttribute("password"));
//删除session中password和它存储的值
session.removeAttribute("password");
System.out.println("=============removeAttribute()===================");
System.out.println("removeAttribute()-->password="+session.getAttribute("password"));
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
(3)session注销
public class TestDemo03SessionServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
//设置session注销
session.invalidate();
System.out.println("==============invalidate()=================");
System.out.println("username="+session.getAttribute("username"));
System.out.println("password="+session.getAttribute("password"));
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
结果:
=============getId()=================
获取sessionID:2219F507CEAD4A01CB2C4715BC9C4EA3
=============getAttribute()===================
getAttribute()-->username=admin
getAttribute()-->username=12345
=============removeAttribute()===================
removeAttribute()-->password=null
==============invalidate()=================
当注销后获取数据时:
三、Session和Cookie
1、Session和Cookie的主要区别
1、Session是服务器技术,Session保用户的数据存储在服务器,每一个用户都有一个唯一的SessionID,每一个用户只可以获取自己Session存储的数据(因为存储在服务器,所有只保存重要的数据,减少浏览器资源的浪费)。
2、Cookie是客户端技术,Cookie把用户的数据保存在浏览器中,可以保存多个。
2、Session使用的场景
1、用户的登录信息。
2、购物车内的数据。
3、整个网站中进场时用到的数据。