会话的概念:
打开一个浏览器,点击多个超链接,访问服务器多个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"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
.img1{
width:160px;
height:140px;
}
.img2{
width:80px;
height:70px;
}
</style>
</head>
<body>
![](/day11/img/1.jpg)<a href="/day11/product?id=1">手电筒</a>
![](/day11/img/2.jpg)<a href="/day11/product?id=2">手机</a>
![](/day11/img/3.jpg)<a href="/day11/product?id=3">电视</a><br>
![](/day11/img/4.jpg)<a href="/day11/product?id=4">冰箱</a>
![](/day11/img/5.jpg)<a href="/day11/product?id=5">手表</a>
![](/day11/img/6.jpg)<a href="/day11/product?id=6">电脑</a><br>
<h3>浏览记录</h3>
<h3><a href="/day11/remove">清除记录</a></h3>
<%
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){
%>
<img class="img2" src="/day11/img/<%= id %>.jpg"><br>
<%
}
}
%>
</body>
</html>
/**
* 浏览商品记录
* @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"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>手电筒<a href="/day11/cart?id=1">加入购物车</a></h3>
<h3>冰箱<a href="/day11/cart?id=2">加入购物车</a></h3>
<h3>电视<a href="/day11/cart?id=3">加入购物车</a></h3>
<h3>电脑<a href="/day11/cart?id=4">加入购物车</a></h3>
<h3>笔记本<a href="/day11/cart?id=5">加入购物车</a></h3>
<h3>手机<a href="/day11/cart?id=6">加入购物车</a></h3>
</body>
</html>
结算页面
<%@page import="java.util.Set"%>
<%@page import="java.util.Map"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>结算页面</h3>
<%
Map<String,Integer> cart = (Map<String,Integer>)request.getSession().getAttribute("cart");
//把商品信息和数量显示到页面上
if(cart != null){
//循环遍历
Set<String> keys = cart.keySet();
for(String key:keys){
%>
<h3>亲,您购物车里的商品是:<%=key %>,数量是<%=cart.get(key) %></h3>
<%
}
}else{
%>
<h3>亲,您还没有购物,请您去<a href="/day11/session/cartList.jsp">败家</a></h3>
<%
}
%>
</body>
</html>
后台实现
/**
* 购物车后台
* @author limaoquan
*
*/
public class CartServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/**
* 1. 购物车 Map<String,Integer> 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<String, Integer> cart = (Map<String, Integer>)session.getAttribute("cart");
//通过cart进行判断,是否是第一次访问
if(cart==null){
//第一次访问
cart = new HashMap<String, Integer>();
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("<h3><a href='/day11/session/cartList.jsp'>继续购物</a></h3>|<h3><a href='/day11/session/pay.jsp'>去结算</a></h3>");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Session追踪,还可以看day12开头的视频
三个域对象
域对象 | 作用应用 |
---|---|
ServletContext | 代表整个web应用,比如存放数据库连接 |
Session | 一次会话,存放个人信息 |
request | 一次请求,存放错误处理 |