会话:用户打开一个浏览器,点击了很多超链接,访问多个web资源,关闭浏览器,这个过程可以称之为会话;
有状态会话:一个同学来过教室,下次再来教室,我们会知道这个同学,曾经来过,称之为有状态会话;
一个网站,怎么证明你来过?
客户端 服务端
cookie
session
常见场景:网站登录之后,你下次不用再登录了,第二次访问直接就上去了!
public class CookieServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决中文乱码问题
resp.setContentType("text/html");
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
//获取cookie
Cookie[] cookies = req.getCookies();
PrintWriter out = resp.getWriter();
if (cookies!=null){
out.print("你上一次访问的时间是:");
for (int i = 0; i <cookies.length ; i++) {
Cookie cookie = cookies[i];
//获取cookie的键
if (cookie.getName().equals("timing")){
//获取cookie的值
long lasteLoginTime = Long.parseLong(cookie.getValue());
Date date = new Date(lasteLoginTime);
out.print(date.toLocaleString());
}
}
}else {
out.print("这是你第一次访问");
}
//创建一个cookie存放上次访问的时间
Cookie cookie = new Cookie("timing",System.currentTimeMillis()+"");
//设置cookie存活时间为1天
cookie.setMaxAge(24*60*60);
//添加cookie
resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
第一次访问
第二次访问
有的浏览器第一次就会有一些cookie,这里用的是Microsoft edge。
Session和cookie的区别:
使用场景:
得到session并向其中存放person对象,输出sessionID信息
public class SessionDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决中文乱码问题
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
req.setCharacterEncoding("utf-8");
//得到Session
HttpSession session = req.getSession();
//向session中存东西
session.setAttribute("person",new Person("伊泽瑞尔",18));
//存放session id
String id = session.getId();
if (session!=null){
resp.getWriter().write("session创建成功,id为:"+id);
}else {
resp.getWriter().write("session已经存在,id为:"+id);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
后台输出session对象信息
public class SessionDemo02 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决中文乱码问题
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
req.setCharacterEncoding("utf-8");
//得到Session
HttpSession session = req.getSession();
Person person = (Person) session.getAttribute("person");
System.out.println(person.toString());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
手动注销session
public class SessionDemo03 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决中文乱码问题
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
req.setCharacterEncoding("utf-8");
//得到Session
HttpSession session = req.getSession();
session.removeAttribute("person");
//手动注销session
session.invalidate();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
设置session失效时间
<session-config>
<session-timeout>1session-timeout>
session-config>
第一次访问页面创建了一个sessionID
访问SessionDemo02后台输出session保存的person对象信息
访问SessionDemo03注销session
再次访问SessionDemo01又新创建了一个session,id和第一次访问的不同。
jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Titletitle>
head>
<body>
<h1>请选择你要购买的书籍h1>
<form action="${pageContext.request.contextPath}/ShoppingCarDemo01" method="get">
<input type="checkbox" name="book" value="JavaSE"/>JavaSE <br/>
<input type="checkbox" name="book" value="JavaWeb"/>JavaWeb <br/>
<input type="checkbox" name="book" value="JavaEE"/>JavaEE <br/>
<input type="submit" value="提交">
form>
body>
html>
处理书籍信息的servlet
public class ShoppingCarDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决中文乱码问题
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
req.setCharacterEncoding("utf-8");
//获取session对象
HttpSession session = req.getSession();
Map<String,Integer> car = (Map<String, Integer>) session.getAttribute("shoppingCar");
if(car==null){
car = new HashMap<>();
}
//获取客户端数据
String[] books = req.getParameterValues("book");
if (books!=null && books.length>0){
for (String book : books) {
if (car.get(book)!=null){
int num = car.get(book);
car.put(book,num+1);
}else {
car.put(book,1);
}
}
}
session.setAttribute("shoppingCar",car);
//重定向到购物车页面
resp.sendRedirect("/demo02_war/ShoppingCarDemo02");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
显示购物车信息的servlet
public class ShoppingCarDemo02 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决中文乱码问题
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
req.setCharacterEncoding("utf-8");
PrintWriter out = resp.getWriter();
//获取session对象
HttpSession session = req.getSession();
Map<String,Integer> car = (Map<String, Integer>) session.getAttribute("shoppingCar");
if (car != null &&car.size()>0){
out.print("您购买的书籍有");
for (String bookName : car.keySet()) {
out.print(""
+bookName+":"+car.get(bookName)+"本"
);
}
}else {
out.print("您还未购买任何书籍");
}
out.print("");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}