2.6、Cookie、Session、登录
4820
一、会话技术简介
会话技术分为Cookie和Session:
Cookie:数据存储在浏览器客户端本地,减少服务器端的存储的压力,安全性不好,客户端可以清除cookieSession:将数据存储到服务器端,安全性相对好,增加服务器的压力
ServletContext域对象的作用范围:整个web应用(所有的web资源servlet、jsp都可以向ServletContext域中存取数据,数据是可以共享的)
context:上下文、应用环境意思
ServletContext是客户端在内存中开辟的一个存取区域,用户购买的产品都放在了ServletContext中,因此后来出现了Session,张三加入购物车的手机,会在Session中开辟一个张三的内存区域,该区域存放着张三的key和value,当张三进行结算时,需要张三携带他的地址值传到Session中就可以找到张三的购物车了,储存张三地址值的技术时Cookie,位于客户端,Session位于服务器端,Session技术要用到Cookie技术
四个域对象:
Request、ServletContext、Session、PageContext 都可以通过setAttribute("key", value)
getAttribute("key")存取数据
什么是域对象?
Request、Session、ServletContext这三个都是域对象,
域对象就是存储数据的区域(其实就是服务器中块内存区域)
所有的域对象都有这三个方法:
request.setAttribute("list", list);request.getAttribute("list");request.removeAttribute("list"):
Request、Session、ServletContext这三个都是域对象区别就是他么的范围不一样。
Request.
request.setAttribute("list",list); requst的范围只在转发中有效。session.setAttribute("list",list); session的范围是当前这个用户的所有操作都有效,servletContext.setAttribute("list".list);servletContext的范围整个顶目都有效
范围:ServletContext>Session>Request>PageContext
使用原则:小的范围能完成功能就放到小的里面。
后面学到用EL表达式进行页面数据读取时,如果多个与都有name属性,那他优先读取小的
一、Cookie
数据放在浏览器端的技术叫Cookie技术:
1、服务器怎么将Cookie设置到浏览器客户端
创建Cookie
Cookie cookie = new Cookie(cookieName, cookieValue)
例子:
Cookie cookie = new Cookie("goods", "IPhone");
resp.addCookie(cookie);
Cookie会以响应头的形式发送给浏览器客户端
Cookie中不能存中文
再请求Servlet的时候会自动携带设置的Cookie:
@WebServlet("/setCookie") public class SetCookieServlet extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("SetCookieServlet.service"); Cookie cookie1 = new Cookie("goods","IPhone"); Cookie cookie2 = new Cookie("name","IPhone"); cookie1.setMaxAge(10*60); resp.addCookie(cookie1); resp.addCookie(cookie2); } }
2、服务器怎么接受客户端携带的Cookie
cookie信息是以请求头的方式发送到服务器端的
1)通过request获得所有的Cookie:
Cookiel cookies =request.getCookies();
2)遍历Cookie数组,通过Cookie的名称获得我们想要的Cookie
@WebServlet("/getCookie") public class GetCookieServlet extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("GetCookieServlet.service"); Cookie[] cookies = req.getCookies(); for (Cookie cookie : cookies) { System.out.println("name:" + cookie.getName() + "values:" + cookie.getValue()); } } }
3、Cookie在浏览器中保存多长时间?
1.默认情况下,当浏览器关闭后,Cookie数据被销毁
2.持久化存储:
cookie.setMaxAge(10*60);//保存10分钟
设置Cookie信息在浏览器的磁盘文件中存储的时间是10分钟,过期浏览器自动删除该Cookie信息
正数:将Cookie数据写到硬盘的文件中。持久化存储。并指定cookie存活时间,时间到后,cookie文件自动失效负数:浏览器关闭的时候Cookie就丢失,默认值零:表示删除同名的Cookie数据。
删除客户端的Cookie:
如果想删除客户端已经存储的Cookie信息,就是将持久化时间设置为0
二、Session
Session服务器端会话技术,在一次会话的多次请求间共亨数据,将数据保存在服务器端的对象中。HttpSession
但客户端需要每次携带一个标识的ID:JSESSIONID去服务器寻找自己的内存空间。
所以说Session技术是基于Cookie技术的,Session需要借助于Cookie存储客户的唯一标识JSESSIONID.
1、获得Session对象
两中getSession方法:
request.getSession(false)
得到session对象,原来有Session就直接返回,没有返回null
request.getSession(true)
创建或得到session对象,原来有Session就直接返回,没有Session自动创建新的session对象
request.getSession();不加参数默认就是true。
2、怎样向session中存取数据
Session也是存储数据的区域对象,所以session对象也具有如下三个方法:
session.setAttribute(String name,Object obj);session.getAttribute(String name);session.removeAttribute(String name);
3、Session对象的生命周期
创建:第一次执行request.getSession()时创建
销毁:
服务器关闭时session过期/失效(默认30分钟)
问题:时间的起算点 从何时开始计算30分钟?
从不操作服务器端的资源开始计时
可以在工程的web.xml中进行配置
30
手动销毁session(注销或者退出)
session.invalidate();
session.removeAttribute("user");
当在同一个浏览器中同时打开多个标签,发送同一个请求或不同的请求,仍是同一个session.
当使用不同的浏览器时,发送请求,即使发送相同的请求,是不同的session;
当把当前某个浏览器的窗口全关闭,再打开,发起相同的请求时,是不同的session.
4、Session与Cookie的区别
Session存储数据在服务器端,Cookie在客户端Session没有数据大小限制,Cookie有Session数据安全,Cookie相对于不安全
三、登录
使用Session技术完成用户登录的功能:
登录功能会使用到Session,把用户登录的用户名和密码保存到Session,因为Session是属于每个用户独有的,就可以记
录每个用户单独的登录信息。
@WebServlet("/user")
public class loginServlet extends HttpServlet {
private IloginService loginService = new LoginServiceImpl();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
String method = req.getParameter("method");
switch (method) {
case "login":
login(req,resp);
break;
case "logout":
logout(req,resp);
break;
}
}
private void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
HttpSession session = req.getSession();
//直接把session销毁
//session.invalidate();
session.removeAttribute("user");
resp.sendRedirect("/login.jsp");
}
private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String name = req.getParameter("name");
String password = req.getParameter("password");
User user = loginService.login(name, password);
if (user == null) {
resp.sendRedirect("fail.jsp");
} else {
HttpSession session = req.getSession();
session.setAttribute("user",user);
resp.sendRedirect("/index.jsp");
}
}
}
//Dao类
public class LoginDaoImpl implements IloginDao {
@Override
public User login(String name, String password) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
User user = null;
try {
connection = JDBCUtil.getConnection();
String sql = "select id,name,password from users where name=? and password=?";
statement = connection.prepareStatement(sql);
statement.setString(1,name);
statement.setString(2,password);
System.out.println(statement);
resultSet = statement.executeQuery();
while (resultSet.next()){
int id = resultSet.getInt("id");
user = new User(id,name,password);
}
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
JDBCUtil.close(connection,statement,resultSet);
}
return user;
}
}
