码迷,mamicode.com
首页 > 其他好文 > 详细

Session和Cookie

时间:2018-07-12 14:35:37      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:技术   values   提取   new   .net   相同   响应头   char   文件   

JSP状态管理

http的无状态性,服务器不会记得发送请求的浏览器是哪一个
保存用户状态的两大机制:session和cookie
Cookie:是web服务器保存在客户端的一系列文本信息
作用:对特定对象的追踪,保存用户浏览记录和习惯,简化登录,容易泄露安全信息
Cookie
Cookie是存储在客户机的文本文件,它们保存了大量轨迹信息。在servlet技术基础上,JSP显然能够提供对HTTP cookie的支持。
方法:
技术分享图片

使用:
创建Cookie对象,名称和值不能包含[ ] ( ) = , " / ? @ : ;
Cookie newCookie = new Cookie(String key,Object values);
设置有效值,调用setMaxAge()函数表明cookie在多长时间(以秒为单位)内有效。
cookie.setMaxAge(606024);
写入Cookie对象,将cookie发送至HTTP响应头中
Response.addCookie(newCookie);
读取Cookie对象
Cookie[] cookie= request.getCookie();

JSP Cookie 处理需要对中文进行编码与解码,方法如下:
String str = java.net.URLEncoder.encode("中文","UTF-8"); //编码
String str = java.net.URLDecoder.decode("编码后的字符串","UTF-8");// 解码
例子:
使用Cookie保存用户信息

<%
request.setCharacterEncoding("utf-8");
//首先判断用户是否选择了记住登录状态
String[] isUserCookies = request.getParameterValues("isUserCookie");
if (isUserCookies != null && isUserCookies.length > 0) {
//把用户名和密码保存在Cookie对象里
String username = URLEncoder.encode(request.getParameter("username"),"utf-8");
//解决无法在Cookie中保存中文字符串的问题(添加java.net.*包)
String password = URLEncoder.encode(request.getParameter("password"),"utf-8");
Cookie usernameCookie = new Cookie("username", username);
Cookie passwordCookie = new Cookie("password", password);
usernameCookie.setMaxAge(864000);
passwordCookie.setMaxAge(864000);//设置最大的生存期间为10天
response.addCookie(usernameCookie);
response.addCookie(passwordCookie);
} else {
Cookie[] cookie = request.getCookies();
if (cookie != null && cookie.length > 0) {
for (Cookie c : cookie) {
if (c.getName().equals("username") || (c.getName().equals("password"))) {
c.setMaxAge(0);//设置保存Cookie失效
response.addCookie(c);//重新保存
}
}
}
}
%>

提取Cookie中的用户信息

<%
request.setCharacterEncoding("utf-8");
String username="";
String password="";
Cookie[] cookie = request.getCookies();
if (cookie != null && cookie.length > 0) {
for (Cookie c : cookie) {
if (c.getName().equals("username")){
username = URLDecoder.decode(c.getValue(),"utf-8");
}
if (c.getName().equals("password")){
password = URLDecoder.decode(c.getValue(),"utf-8");
}
}
}
%>

Session

技术分享图片

session和Cookie的区别

1相同点,都会保存用户状态,都会过期
2区别 session在服务端保存用户信息,Cookie在客户端保存用户信息;session保存的是Object类型,Cookie保存的是String类型;session随着会话的结束而将其数据销毁,Cookie可以长期的保存在客户端;session一般保存是重要的用户信息,Cookie保存不重要的用户信息。

Session和Cookie

标签:技术   values   提取   new   .net   相同   响应头   char   文件   

原文地址:https://www.cnblogs.com/ww11/p/9299163.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!