目录
27. Cookie、Session、登录
1. 会话技术简介:
链接到数据库Connection,也叫会话,你要想操作数据库要和数据库保持一个会话的功能。
●
会话管理: 管理浏览器客户端 和 服务器端之间会话过程中产生的会话数据(Cookie、Session)
●
数据放在服务器的技术叫Session技术:Session技术要用到Cookie
●
四个域对象:
Request、ServletContext、Session 都可以通过setAttribute("key", value) getAttribute("key")
Requst中setAttribute只在转发过程中有效
Request<Session<ServletContext
●
数据放在浏览器端的技术叫Cookie技术:
Session技术用到Cookie技术,SessionID是保存到浏览器的Cookie。
像亚马逊这种电商网站,用户没有登录时候,购物车信息是存放在Cookie中,如果用户登录了,会把Cookie中购物车信息 同步到服务器的数据库中,
是不会放到Session中,因为像ServletContext和Session都是
服务器中的一块内存区域是非常宝贵,重启服务器所有的内存区域都会销毁,数据也就没有
。
大家都有这种体验登录之后加入在电脑浏览器
加入购物车信息,在手机上也能访问,手机上是从服务器的数据库中拿到的。
● 会话技术
从打开一个浏览器访问某个站点,到关闭这个浏览器的整个过程,成为一次会话
。
会话技术就是记录这次会话中客户端的状态与数据的。
会话技术
分为Cookie和Session:
Cookie:数据存储在客户端本地,减少服务器端的存储的压力,安全性不好,客户端可以清除cookie。
Session:将数据存储到服务器端,安全性相对好,但会增加服务器的压力。
2. Cookie:
● 服务器怎么将Cookie设置到浏览器客户端:
创建Cookie
Cookie cookie = new Cookie(cookieName, cookieValue);
例子:
Cookie cookie = new Cookie("goods", "IPhone");
resp.addCookie(cookie);
Cookie会以响应头的形式发送给浏览器客户端。
Cookie中不能存中文。
再请求Servlet的时候会自动携带设置的Cookie:
● 服务器怎么接受客户端携带的Cookie
cookie信息是以请求头的方式发送到服务器端的:
1)通过request获得所有的Cookie:
Cookie[] cookies = request.getCookies();
2)遍历Cookie数组,通过Cookie的名称获得我们想要的Cookie
protected void service(HttpServletRequest req, HttpServletResponse resp) {
Cookie[] cookies = req.getCookies();
for (Cookie cookie : cookies) {
System.out.println("name: " + cookie.getName() + ", value: " + cookie.getValue());
}
}
● 设置Cookie在客户端的持久化时间:
cookie.setMaxAge(10 * 60);//保存10分钟
设置Cookie信息在浏览器的磁盘文件中存储的时间是10分钟,过期浏览器自动删除该Cookie信息。
an integer specifying the maximum age of the cookie in seconds; if negative, means the cookie is not stored; if zero, deletes the cookie
正数:保存的时间
负数:浏览器关闭的时候Cookie就丢失
零:表示删除同名的Cookie数据。
● 删除客户端的Cookie:
如果想删除客户端已经存储的Cookie信息,就是将持久化时间设置为0
● 案例:记录上一次访问网站的时间
如果是第一次就显示:您是第一次访问
如果之前访问过:显示上一次访问时间
@WebServlet("/lastAccessTime")
public class LastAccessTimeServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session1 = req.getSession();
HttpSession session2 = req.getSession(true);
HttpSession session3 = req.getSession(false);
// 现在设置的访问时间,当下一次访问的时候就变成上一次的访问时间
Date date = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-ddhh:mm:ss");
String time = format.format(date);
Cookie cookie = new Cookie("lastAccessTime", time);
resp.addCookie(cookie);
// 拿到上次访问的时间,在浏览器展示
String lastAccessTime = "";
Cookie[] cookies = req.getCookies();
if (cookies != null && cookies.length != 0) {
for (Cookie cook : cookies) {
String name = cook.getName();
if (name.equals("lastAccessTime")) {
lastAccessTime = cook.getValue();
break;
}
}
}
// 解决服务器返回给浏览器中文乱码问题
resp.setContentType("text/html;charset=utf-8");
PrintWriter writer = resp.getWriter();
writer.println("您上一次访问的时间: " + lastAccessTime);
}
}
3. Session:
● Cookie的局限:
1)Cookie只能存字符串类型。不能保存对象
2)不能存中文。
3)1个Cookie的容量不超过4KB。
如果要保存非字符串,超过4kb内容,只能使用session技术!!!
Session特点:会话数据保存在服务器端。
(内存中)
Session技术是将数据存储到服务器端的技术,会为每个客户端都创建一块内存空间存储客户的数据,
但客户端需要每次携带一个标识的ID:JSESSIONID去服务器寻找自己的内存空间。
所以说Session
技术是基于Cookie技术的,Session需要借助于Cookie存储客户的唯一标识JSESSIONID。
● 获得Session对象
两中getSession方法:
HttpSession session = request.getSession(true) / request.getSession(false) :
request.getSession(false):得到session对象。原来有Session就直接返回,没有返回null
request.getSession(true):创建或得到session对象。原来有Session就直接返回,没有Session自动创建新的session对象。
此方法会获得专属于当前会话的Session对象,如果服务器端没有该会话的Session 对象会创建一个新的Session返回,如果已经有了属于该会话的Session直接将已有的Session返回(实质就是根据JSESSIONID判断该客户端是否在服务器上已经存在 session了)
request.getSession();不加参数默认就是true。
● 怎样向session中存取数据
Session也是存储数据的区域对象,所以session对象也具有如下三个方法:
session.setAttribute(String name,Object obj);
session.getAttribute(String name);
session.removeAttribute(String name);
● Session对象的生命周期
创建:第一次执行request.getSession()时创建
销毁:
1)服务器关闭时
2)session过期/失效(默认30分钟)
如果不停的清空客户端的sessionid,然后在请求,就会在服务器产生很多的垃圾session区域,浪费资源。
void setMaxInactiveInterval(int interval) : 设置session的有效时间
session对象销毁时间:
1、 默认情况30分服务器自动回收
2、 修改session回收时间
3、 全局修改session有效时间
问题:时间的起算点 从何时开始计算30分钟?
从不操作服务器端的资源开始计时
可以在
工程的web.xml中进行配置
<session-config>
<session-timeout>30</session-timeout>
</session-config>
3)手动销毁session (注销或者退出)
session.invalidate();
默认在一次会话中,也就是说在,一次会话中任何资源公用一个session对象
● 面试题:浏览器关闭,session就销毁了? ×
● 使用Session技术完成用户登录的功能:
登录功能会使用到Session,把用户登录的用户名和密码保存到Session,因为Session是属于每个用户独有的,就可以记录每个用户单独的登录信息。
UserServlet.java:
@WebServlet("/user")
public class UserServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getParameter("method");
switch (method) {
case "login":
login(req, resp);
break;
}
}
private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
System.out.println("UserServlet.login");
String name = req.getParameter("name");
String password = req.getParameter("password");
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
User user = null;
try {
connection = JDBCUtil.getConnection();
String sql = "select id,name,password,age,level from user where name=? and password=?";
statement = connection.prepareStatement(sql);
statement.setString(1, name);
statement.setString(2, password);
resultSet = statement.executeQuery();
if (resultSet.next()) {
int id = resultSet.getInt("id");
int age = resultSet.getInt("age");
int level = resultSet.getInt("level");
user = new User(id, name, password, age, level);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JDBCUtil.close(connection, statement, resultSet);
}
if (user != null) { // 有这个用户登录成功
HttpSession session = req.getSession();
session.setAttribute("user", user);
// /JavaWeb/
resp.sendRedirect(req.getContextPath() + "/");
} else { // 用户名或者密码错误,没有这个用户
resp.sendRedirect(req.getContextPath() + "/fail.html");
}
}
}
login.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="<%=request.getContextPath()%>/user?method=login" method="post">
用户名:<input type="text" name="name"/> <br/>
密码:<input type="password" name="password"/> <br/>
<input type="submit" value="登录"/>
</form>
</body>
</html>