您的位置:首页 > 其它

Web开发之Cookie and Session

2016-01-18 15:56 344 查看


会话


什么是会话?

简单说:用户开一个浏览器,点击多个超链接,访问服务器的多个web资源,然后关闭浏览器,整个过程就称之为一个会话。


会话过程要解决什么问题

每个用户在使用浏览器与服务器进行会话的过程中,都会产生一些数据,程序要想办法为每个用户保存这些数据
例如:用户点击超链接通过一个servlet购买了一个商品,程序应该想办法保存用户购买的商品,以便用户点结账servlet时,结账servlet可以得到用户购买的商品为用户结账。


Cookie


Cookie的属性

name:Cookie的名字
value:Cookie的值
path:Cookie的存储路径,默认是访问的Servlet所在路径(可选)
MaxAge:最大的存活时间,默认是存放在缓存区中的,生命周期就是一个会话(可选)
version:Cookie的版本
domain:域名(哪个网站)
Comment:备注


Cookie的相关用法

程序为:记录上次访问的时间

ServletCookie1中
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

out.write("您上次访问的时间是:");
//拿到客户端携带的记录上次访问时间的Cookie:假设Cookie的名字是lastaccesstime,值是一个long类型的值
//拿到客户端携带的所有的Cookie
Cookie[] cs = request.getCookies();
//循环判断拿到需要的Cookie
for (int i=0; cs!=null && i<cs.length; i++){
Cookie c = cs[i];
if(c.getName().equals("lastaccesstime")){
//说明找到了需要的Cookie
String time = c.getValue();
//将time转化为long类型的值
long t = Long.parseLong(time);
//格式化为我们需要的格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//创建一个date对象
Date d = new Date(t);
//将数据输出到页面
out.write(sdf.format(d) + "  
<a href = 'request.getContextPath()+"/servlet/ServletCookie2"'>清除Cookie</a>");
}
//向客户端发送Cookie
Cookie c = new Cookie("lastaccesstime", new Date().getTime() + "");

//设置Cookie的存活时间
//(只要设置了此时间,此Cookie就将存储到客户端的硬盘上,不会在缓存中存储)
c.setMaxAge(Integer.MAX_VALUE);

//设置浏览器携带Cookie的路径
c.setPath(request.getContextPath());

//设置路径如果是/,意味着访问服务器上的任意工程资源都会携带此Cookie
//c.setPath("/");   //此路径是服务器的根路径:协议+主机名+端口号

//发送到客户端
response.addCookie(c);
}


ServletCookie2中(删除存储的Cookie)
//sun公司没有提供相应的方法
//所以创建一个同名的cookie,将存活时间设置为0即可,然后覆盖客户端存储的cookie
Cookie c = new Cookie("lastaccesstime","");
c.setMaxAge(0);

//设置路径
c.setPath(request.getContextPath());

//发送到客户端
response.addCookie(c);


ServletCookie3(演示path的含义)

path的含义:默认情况下,客户端存储的Cookie的路径就是发送Cookie的Servlet的路径

//拿到客户端所有的Cookie
Cookies[] cs = request.getCookies();
//拿到记录上次访问时间的Cookies
for(int i=0; cs!=null && i<cs.length; i++)  {
Cookie c = cs[i];
if(c.getName().equals("lastaccesstime")){
String value = c.getValue();
out.write(value);
}
}



Cookie应用:记住用户名密码

ServletUI中:

创建一个登录页面

request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

//拿到错误信息
String error = (String)request.getAttribute("error");
if(error != null)
out.write("<font color = red>" +error+ "</font>");

String username="";
String pass = "";

//拿到客户端携带的所有Cookie
Cookie[] cs = request.getCookies();
//循环判断
for(int i=0; cs!=null && i<cs.length; i++){
Cookie c = cs[i];
if(c.getName().equals("name")){
//说明找到了存储用户名的cookie
username = c.getValue();
}
if(c.getName().equals("pass"))
//说明找到了存储密码的cookie
pass = c.getValue();
}

//创建登录页面
out.write("<form action = '" + request.getContextPath() +
"/servlet/LoginServlet"' method = 'post'>");
out.write("姓名:<input type = 'text' name = 'username' value = '"+ username + "'><br>");
out.write("密码:<input type = 'text' name = 'password' value = '"+ pass + "'><br>");
out.write("<input type = 'checkbox'
name = 'remember' value = 'on'>记住用户名及密码两周<br>");
out.write("<input type = 'submit' value = '登录'><br>");


LoginServlet中:

1.判断用户是否是合法用户

2.看用户是否选择了记录用户名和密码

//拿取浏览器传递的数据
String name = request.getParameter("username");
String pass = request.getParameter("password");
String remember = request.getParameter("remember");

//判断用户是否是合法用户:假定name和pass的依序一样就是合法
//拿到密码的逆序
String pass1 = new StringBuffer(pass).reverse().toString();

//判断
if(name.equals(pass1)){
//表示合法

Cookie c = new Cookie("name",name);
Cookie c1 = new Cookie("pass",pass);

//判断用户是否选择了记住用户名和密码
if("on".equals(remember)){
//说明用户选择了记录

//设定存储到客户端的硬盘上
c.setMaxAge(Integer.MAX_VALUE);
c1.setMaxAge(Integer.MAX_VALUE);
}else{
//设定客户端存储的用户名和密码立刻失效
c.setMaxAge(0);
c1.setMaxAge(0);
}
//设定访问路径
c.setPath(request.getContextPath());
c1.setPath(request.getContextPath());

//向客户端发送Cookie
response.addCookie(c);
response.addCookie(c1);

request.setAttribute("name", name);
request.getRequestDispatcher("MainServlet").forward(request, response);
}else{
//非法用户
request.setAttribute("error", "用户名或密码错误");
request.getRequestDispatcher("ServletUI").forward(request,response);
}


MainServlet中:
String name = (String)request.getAttribute("name");

out.write(name + "欢迎你");



Session(也是域对象)

在Web开发中,服务器为每个用户创建一个会话对象(session对象),即一个浏览器独占一个session对象(默认)。因此,在需要保存用户数据时,服务器程序可以把用户数据写到用户浏览器独占的session中,当用户使用浏览器访问其它程序时,其它程序可以从用户的session中取出该用户的数据,为用户服务。


创建session

Servlet1

1.看客户端是否携带了JSESSIONIDCookie

2.如果没有携带,创建一个新的session对象,并分配一个唯一的id,发送到客户端,存储在客户端的缓存中;

如果携带了,将根据cookie的值(id)到服务器的内存中寻找session,如果找到了则返回此session为客户端服务,如果找不到,则创建新的session对象,并分配一个唯一的id,发送到客户端,存储在客户端的缓存中

HttpSession session = request.getSesstion();
String id = session.getId();
System.out.println("id:" + id);
session.setAttribute("name", "Tryking");


Servlet2

如果先访问1,不关浏览器再访问2。则两个id的值是一样的

HttpSession session = request.getSession();
String id = session.getId();
System.out.println("id:" + id);
String name = (String)session.getAttribute("name");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: