会话的概念:
打开一个浏览器,点击多个超链接,访问服务器多个web资源,然后关闭浏览器,整个过程称之为一个会话。
Cookie快速入门
- 显示上次的访问时间
- 第一次访问,输出欢迎
- 第二次访问,输出上次的访问时间,并把本次访问时间存入到cookie
public class LastServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//设置字符中文乱码问题
response.setContentType("text/html;charset=utf-8");
//获取所有的cookie,判断是否是第一次访问
Cookie[] cookies = request.getCookies();
//通过制定cookie名称来查找cookie Cookie c = new Cookie("last","当前时间")
Cookie cookie = MyCookieUtil.getCookieByName(cookies,"last");
//判断,如果cookie是null,说明第一次访问
if(cookie == null){
response.getWriter().write("欢迎第一次来,以后再来");
//Cookie newCookie = new Cookie("last",);
}else{
String value = cookie.getValue();
response.getWriter().write("你又来了,上次的时间是" + value);
}
//记录当前的时间
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String sDate = sdf.format(date);
Cookie newcookie = new Cookie("last",sDate);
//回写
response.addCookie(newcookie);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
//第二个文件
public class MyCookieUtil {
public static Cookie getCookieByName(Cookie[] cookies,String name){
if(cookies == null){
return null;
} else {
//循环遍历
for(Cookie cookie:cookies){
//获取cookie的名称
if(cookie.getName().equals(name)){
return cookie;
}
}
}
return null;
}
}
Cookie的常用API
//设置有效时间就成为持久cookie,1小时后才会消失
newcookie.setMaxAge(60*60);//单位秒,1小时后才会消失
//设置有效路径
newcookie.setPath("/day11");//day11下面的所有东西,访问时都会带着此cookie
示例代码
界面的jsp文件
<%@page import="cn.utils.MyCookieUtil"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
Insert title here
![](/day11/img/1.jpg)手电筒
![](/day11/img/2.jpg)手机
![](/day11/img/3.jpg)电视
![](/day11/img/4.jpg)冰箱
![](/day11/img/5.jpg)手表
![](/day11/img/6.jpg)电脑
浏览记录
清除记录
<%
Cookie[] cookies = request.getCookies();
Cookie cookie = MyCookieUtil.getCookieByName(cookies, "product");
//如果cookie不为空,取值
if(cookie != null){
String value = cookie.getValue();
String[] ids = value.split(",");
for(String id:ids){
%>
<%
}
}
%>
/**
* 浏览商品记录
* @author limaoquan
*
*/
public class ProductServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/**
* 1.获取请求参数
* 2.获取cookie数组,通过指定的名称查找cookie
* 3.如果cookie==null,第一次访问
* * 创建cookie,回写到浏览器
* 4.如果cookie!=null
* * 判断当前的id是否已经存在cookie的value
* * 如果不存在,就追加;存在,不追加
* 5. 重定向到商品界面
*/
String id = request.getParameter("id");
Cookie[] cookies = request.getCookies();
Cookie cookie = MyCookieUtil.getCookieByName(cookies, "product");
if(cookie==null){
Cookie newcookie = new Cookie("product", id);
newcookie.setMaxAge(60*60*24*7);//7天
newcookie.setPath("/");//
response.addCookie(newcookie);
}else{
String value = cookie.getValue();
String[] ids = value.split(",");
if(!checkId(ids,id)){
//不包含
cookie.setValue(value + "," + id);
cookie.setMaxAge(60*60*24*7);//7天
cookie.setPath("/");
response.addCookie(cookie);
}
}
//重定向
response.sendRedirect("/day11/cookie/productList.jsp");
}
private boolean checkId(String[] ids, String id) {
for(String str:ids){
if(str.equals(id)){
return true;
}
}
return false;
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
/**
* 清除cookie
* @author limaoquan
*
*/
public class RemoveServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//获取cookie
//第二种方式创建cookie,名称相同,覆盖掉客户端的cookie
Cookie cookie = new Cookie("product", "");
//设置有效时间
cookie.setMaxAge(0);
cookie.setPath("/");//创造时设置过路径,删除必须设置完全相同的路径
response.addCookie(cookie);
response.sendRedirect("/day11/cookie/productList.jsp");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Session
常见API
setAttribute(String name, Object value)
Object getAttribute(String name)
String getId() 获取session的唯一ID
void invalidate() 销毁的session
示例购物车简单实现
购物页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
Insert title here
手电筒加入购物车
冰箱加入购物车
电视加入购物车
电脑加入购物车
笔记本加入购物车
手机加入购物车
结算页面
<%@page import="java.util.Set"%>
<%@page import="java.util.Map"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
Insert title here
结算页面
<%
Map cart = (Map)request.getSession().getAttribute("cart");
//把商品信息和数量显示到页面上
if(cart != null){
//循环遍历
Set keys = cart.keySet();
for(String key:keys){
%>
亲,您购物车里的商品是:<%=key %>,数量是<%=cart.get(key) %>
<%
}
}else{
%>
亲,您还没有购物,请您去败家
<%
}
%>
后台实现
/**
* 购物车后台
* @author limaoquan
*
*/
public class CartServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/**
* 1. 购物车 Map cart, 把购物车存入到session中
* 2. 先从session中获取购物车,判断是否是第一次访问
* 3. 第一次访问,创建购物车,把商品名称和数量加入到购物车,存入到session中
* 4. 如果包含,数量+1,存入到session中
* 5. 继续购物或者结算
*/
//获取参数
String id = request.getParameter("id");
//购物车存入商品的名称和数量
String[] names = {"手电筒","冰箱","电视","电脑","笔记本","手机"};
//把id翻译成名称
int idx = Integer.parseInt(id);
String name = names[idx-1];
//从session中获取购物车,先获取session
HttpSession session = request.getSession();
Map cart = (Map)session.getAttribute("cart");
//通过cart进行判断,是否是第一次访问
if(cart==null){
//第一次访问
cart = new HashMap();
cart.put(name, 1);
//存入到session中
session.setAttribute("cart", cart);
}else{
//是否包含该商品
if(cart.containsKey(name)){
//包含
//取出数量+1
Integer count = cart.get(name);
count++;
cart.put(name, count);
//存入到session中
session.setAttribute("cart", cart);
}else{
//不包含
cart.put(name, 1);
//存入到session中
session.setAttribute("cart", cart);
}
}
//继续购物或者结算
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write("继续购物
|去结算
");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Session追踪,还可以看day12开头的视频
三个域对象
域对象 | 作用应用 |
---|---|
ServletContext | 代表整个web应用,比如存放数据库连接 |
Session | 一次会话,存放个人信息 |
request | 一次请求,存放错误处理 |