当前位置:网站首页>使用cookie技术实现历史浏览记录并控制显示的个数
使用cookie技术实现历史浏览记录并控制显示的个数
2022-06-30 11:06:00 【全栈程序员站长】
使用cookie技术实现历史浏览记录, 并且只显示3个历史浏览记录,每次访问的记录都放到最前main。 需要了解cookie的知识点: cookie保存在客户端; 服务端创建好cookie (Cookie cookie = new Cookie(String cookieName,String cookieValue), 使用response.add(Cookie)返回给客户端;下一次访问的时候浏览器会携带这个cookie和请求参数一起发送给服务端。服务端接收cookie使用request.getCookies();返回的是Cookie [] .使用的时候需要判断这个cookie是否为null。
cookie的有效期:cookie.setMaxAge(0) ,response.addCookie(cookie);告诉浏览器cookie失效。 开始上代码: 第一步:准备数据:
import java.util.HashMap; import java.util.Map;
import com.itmayiedu.bean.Book; /**
- 模拟数据库中的数据
- @author Administrator
*/ public class DBUtils { private static Map<Integer, Book> books = new HashMap();
static{
books.put(1, new Book(1,"java入门学习","tom"));
books.put(2, new Book(2, "c#", "jack"));
books.put(3, new Book(3, "python", "marray"));
books.put(4, new Book(4,"大数据","kevin"));
books.put(5, new Book(5, "javascipt入门", "lilie"));
}
public static Map<Integer, Book> getBookAll(){
return DBUtils.books;
}
//根据id 获取书籍信息 key 就是数的id。
public static Book getBookById(Integer id){
return books.get(id);
}}
第二步: import java.io.IOException; import java.io.PrintWriter; import java.util.Map; import java.util.Map.Entry; import java.util.Set;
import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
import com.itmayiedu.bean.Book; import com.itmayiedu.util.DBUtils;
/**
- 在浏览器中显示我们需要访问的数据
- @author Administrator
*/
@WebServlet(“/showBookAll”) public class ShowBookAll extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
//显示所有的书籍
PrintWriter writer = response.getWriter();
writer.println("图书列表:");
Map<Integer, Book> bookMap = DBUtils.getBookAll();
Set<Entry<Integer,Book>> entrySet = bookMap.entrySet();
for (Entry<Integer, Book> entry : entrySet) {
Book book = entry.getValue();
writer.print("<br/><a href='http://localhost:8080"+request.getContextPath()+"/bookView?id="+book.getId()+"'>"+book.getName()+"</a>");
}
writer.println("<br/>访问的历史记录<br/>");
//获取cookie
Cookie[] cs = request.getCookies();
if(cs !=null){
for (Cookie c : cs) {
if("historyIDs".equals(c.getName())){
String historyIDs = c.getValue();
String[] split = historyIDs.split("-");
for (String id : split) {
Book book = DBUtils.getBookById(Integer.parseInt(id));
writer.println("<br><a href='http://localhost:8080"+request.getContextPath()+"/bookView?id="+book.getId()+"'>"+book.getName()+"</a>");
}
}
}
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}}
第三步: import java.io.IOException; import java.util.Arrays; import java.util.LinkedList; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
import com.itmayiedu.bean.Book; import com.itmayiedu.util.DBUtils;
/**
- 详情信息处理
- @author Administrator
*/
@WebServlet(“/bookView”) public class BookViewServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(“text/html;charset=utf-8”); // 获取id String idStr = request.getParameter(“id”); System.out.println(“现在访问的id:” + idStr); Book book = DBUtils.getBookById(Integer.parseInt(idStr));
response.getWriter().println("详细信息:" + book.toString());
LinkedList<String> list = new LinkedList<>();
StringBuffer sb = new StringBuffer();
// TODO 记录浏览信息,把id保存在cookie中,显示在页面
// 把访问的id放入到cookie中
Cookie[] cs = request.getCookies();
if (cs != null) {
// 说明原来已经有cookie其中保存了id
// historyIDs = 1-2-3-4
// 1-2-3-4-1 1-2-3-4-4 1-2-3-4 3
for (Cookie c : cs) {
if ("historyIDs".equals(c.getName())) {
String idValues = c.getValue();
System.out.println("以前访问的histroyIDs:" + idValues);
// 页面只显示3个
String[] ids = idValues.split("-");
System.out.println("分割后的数组:" + Arrays.toString(ids));
for (String id : ids) {
list.add(id);
}
System.out.println("原来的集合元素:" + list);
// 控制只添加三个id
if (!list.contains(idStr)) {
// 不包含重复元素
if (list.size() == 3) {
// 里面的元素等于3
list.removeFirst();
}
} else {
// 包含了重复的元素
list.remove(idStr);
}
list.addFirst(idStr);
System.out.println("添加新的id之后的集合元素:" + list);
for (String id : list) {
sb.append(id + "-");
}
idValues = sb.substring(0, sb.length() - 1);
System.out.println("拼接后的histroyIDs:" + idValues);
c.setValue(idValues);
response.addCookie(c);
/*
* //如果第一次访问和后来有范问同一个就直接结束方法 if
* (idValues.equals(idStr)){return;}
*
* if(idValues.startsWith(idStr)){ idValues =
* idValues.replaceAll(idStr+"-", ""); }else{ idValues =
* idValues.replaceAll("-"+idStr, ""); }
*
*
*
*
* idValues += "-" + idStr;
*
* System.out.println("现在histroyIDs:" + idValues); //
* 设置cookie的值 c.setValue(idValues); response.addCookie(c);
*/
}
}
} else {
// 说明没有创建cookie
Cookie cookie = new Cookie("historyIDs", idStr);
cookie.setMaxAge(60 * 1);
response.addCookie(cookie);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}}
备注: 可以使用字符串形式来拼接historyIds;字符串形式没有控制显示访问历史记录,我是使用LinkedList集合来控制,每次访问新都插入在第一个位置,所有选择了LinkedList集合,它可以控制插入位置和插入在首行和末尾,也可以删除指定位置和首末位置的元素。
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/100800.html原文链接:https://javaforall.cn
边栏推荐
- dplyr 中的filter报错:Can‘t transform a data frame with duplicate names
- Database transactions
- Esp32-c3 introductory tutorial question ⑨ - core 0 panic 'ed (load access fault) Exception was unhandled. vfprintf. c:1528
- R语言去重操作unique duplicate filter
- 【leetcode 16】三数之和
- 数据库 级联操作
- datax json说明
- 优惠券种类那么多,先区分清楚再薅羊毛!
- HMS Core音频编辑服务3D音频技术,助力打造沉浸式听觉盛宴
- [applet practice series] Introduction to the registration life cycle of the applet framework page
猜你喜欢

据说用了这个,老板连夜把测试开了

Handler source code analysis

暑假学习记录

“新数科技”完成数千万元A+轮融资,造一体化智能数据库云管理平台

R语言查看版本 R包查看版本
![200000 bonus pool! [Alibaba security × ICDM 2022] the risk commodity inspection competition on the large-scale e-commerce map is in hot registration](/img/0e/19c4c97a582d7b2ad08ce806d7af03.jpg)
200000 bonus pool! [Alibaba security × ICDM 2022] the risk commodity inspection competition on the large-scale e-commerce map is in hot registration

EMC surge

How to analyze native crash through GDB

ESP32-C3入门教程 问题篇⑨——Core 0 panic‘ed (Load access fault). Exception was unhandled. vfprintf.c:1528

关于IP定位查询接口的测评Ⅲ
随机推荐
ESP32-C3入门教程 基础篇⑪——Non-Volatile Storage (NVS) 非易失性存储参数的读写
The operation and maintenance security gateway (Fortress machine) of Qiming star group once again won the first place!
LiveData源码赏析三 —— 常见问题
What is erdma as illustrated by Coptic cartoon?
Flutter start from scratch 008 form
数学(快速幂)
线代(高斯消元法、线性基)
【IC5000教程】-01-使用daqIDEA图形化debug调试C代码
Go语言学习之Switch语句的使用
[IC5000 tutorial] - 01- use daqdea graphical debug to debug C code
200000 bonus pool! [Alibaba security × ICDM 2022] the risk commodity inspection competition on the large-scale e-commerce map is in hot registration
单片机 MCU 固件打包脚本软件
[leetcode 239] sliding window
Use of switch statement in go language learning
【leetcode 16】三数之和
Summer vacation study record
Go language defer
OceanBase 安装 yum 源配置错误及解决办法
ESP32-C3入门教程 问题篇⑨——Core 0 panic‘ed (Load access fault). Exception was unhandled. vfprintf.c:1528
数据库 事务