当前位置:网站首页>Using cookie technology to realize historical browsing records and control the number of displays
Using cookie technology to realize historical browsing records and control the number of displays
2022-06-30 11:43:00 【Full stack programmer webmaster】
Use cookie Technology enables historical browsing records , And only show 3 History browsing records , The records of each visit are put at the top main. Need to know cookie Knowledge points of : cookie Save on client ; The server is created cookie (Cookie cookie = new Cookie(String cookieName,String cookieValue), Use response.add(Cookie) Return to the client ; The next time you visit, the browser will carry this cookie Send it to the server together with the request parameters . Server receive cookie Use request.getCookies(); The return is Cookie [] . You need to judge this when using it cookie Is it null.
cookie The validity of the :cookie.setMaxAge(0) ,response.addCookie(cookie); Tell the browser cookie invalid . Start coding : First step : Prepare the data :
import java.util.HashMap; import java.util.Map;
import com.itmayiedu.bean.Book; /**
- Simulate the data in the database
- @author Administrator
*/ public class DBUtils { private static Map<Integer, Book> books = new HashMap();
static{
books.put(1, new Book(1,"java Introduction learning ","tom"));
books.put(2, new Book(2, "c#", "jack"));
books.put(3, new Book(3, "python", "marray"));
books.put(4, new Book(4," big data ","kevin"));
books.put(5, new Book(5, "javascipt introduction ", "lilie"));
}
public static Map<Integer, Book> getBookAll(){
return DBUtils.books;
}
// according to id Get book information key Just count id.
public static Book getBookById(Integer id){
return books.get(id);
}
}
The second step : 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;
/**
- Display the data we need to access in the browser
- @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");
// Show all books
PrintWriter writer = response.getWriter();
writer.println(" The book list :");
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/> History of the visit <br/>");
// obtain 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);
}
}
The third step : 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;
/**
- Detailed information processing
- @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”); // obtain id String idStr = request.getParameter(“id”); System.out.println(“ Now visit id:” + idStr); Book book = DBUtils.getBookById(Integer.parseInt(idStr));
response.getWriter().println(" Details :" + book.toString());
LinkedList<String> list = new LinkedList<>();
StringBuffer sb = new StringBuffer();
// TODO Record browsing information , hold id Save in cookie in , Show on page
// Put the visited id Put in cookie in
Cookie[] cs = request.getCookies();
if (cs != null) {
// It means that there are already cookie It's preserved 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(" Previously visited histroyIDs:" + idValues);
// Page display only 3 individual
String[] ids = idValues.split("-");
System.out.println(" Split array :" + Arrays.toString(ids));
for (String id : ids) {
list.add(id);
}
System.out.println(" The original set element :" + list);
// Control adds only three id
if (!list.contains(idStr)) {
// No repeating elements
if (list.size() == 3) {
// The elements inside are equal to 3
list.removeFirst();
}
} else {
// Contains duplicate elements
list.remove(idStr);
}
list.addFirst(idStr);
System.out.println(" Add new id Subsequent collection elements :" + list);
for (String id : list) {
sb.append(id + "-");
}
idValues = sb.substring(0, sb.length() - 1);
System.out.println(" After splicing histroyIDs:" + idValues);
c.setValue(idValues);
response.addCookie(c);
/*
* // If the first visit is the same as the later one, the method will be ended directly if
* (idValues.equals(idStr)){return;}
*
* if(idValues.startsWith(idStr)){ idValues =
* idValues.replaceAll(idStr+"-", ""); }else{ idValues =
* idValues.replaceAll("-"+idStr, ""); }
*
*
*
*
* idValues += "-" + idStr;
*
* System.out.println(" Now? histroyIDs:" + idValues); //
* Set up cookie Value c.setValue(idValues); response.addCookie(c);
*/
}
}
} else {
// Description... Was not created 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);
}
}
remarks : You can use string form to splice historyIds; The string format does not control the display of access history , I use it. LinkedList Set to control , The new is inserted in the first position every time you visit , All the choices LinkedList aggregate , It can control the insertion position and insertion at the beginning and end of the line , You can also delete the elements at the specified position and the first and last positions .
Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/100800.html Link to the original text :https://javaforall.cn
边栏推荐
- Speech signal processing - Fundamentals (V): Fourier transform
- 100 important knowledge points that SQL must master: join table
- Boost研究:Boost Log
- Digitalization is not a trial, but a wading out of "Xingzhi Digital China" × History of Foxconn
- Webview,ScrollView滑动冲突咋整
- H3C switch emptying configuration
- 揭秘得物客服IM全链路通信过程
- Speech recognition - Fundamentals (I): introduction [speech to text]
- CVPR 2022 | 大幅减少零样本学习所需人工标注,马普所和北邮提出富含视觉信息的类别语义嵌入...
- Flutter 从零开始 004 按钮组件
猜你喜欢
8 lines of code to achieve quick sorting, easy to understand illustrations!
揭秘得物客服IM全链路通信过程
限时预约|6 月 Apache Pulsar 中文开发者与用户组会议
wallys/IPQ8074a/2x(4×4 or 8×8) 11AX MU-MIMO DUAL CONCURRENT EMBEDDEDBOARD
There are so many kinds of coupons. First distinguish them clearly and then collect the wool!
1175. prime permutation
相对位置编码Transformer的一个理论缺陷与对策
基于视觉的机器人抓取:从物体定位、物体姿态估计到平行抓取器抓取估计
koa - 洋葱模型浅析
R language de duplication operation unique duplicate filter
随机推荐
[revisiting the classic C language] ~x,%c,%d,%x, etc. in C language, the role of the address character in C language, and the consortium in C language
Digitalization is not a trial, but a wading out of "Xingzhi Digital China" × History of Foxconn
数据库 自动增长
Database transactions
Introduction to China Mobile oneos development board
Dameng data rushes to the scientific innovation board, or becomes the "first share of domestic database" in the A-share market
揭秘得物客服IM全链路通信过程
Introduction to game theory
Esp32-c3 introductory tutorial basic part ⑪ - reading and writing non-volatile storage (NVS) parameters
19年来最艰难的618,徐雷表达三个谢意
In depth analysis of Apache bookkeeper series: Part 4 - back pressure
启明星辰集团运维安全网关(堡垒机)再次夺得榜首!
R语言查看版本 R包查看版本
What is erdma as illustrated by Coptic cartoon?
“新数科技”完成数千万元A+轮融资,造一体化智能数据库云管理平台
Oracle netsuite helps TCM bio understand data changes and make business development more flexible
【西安交通大学】考研初试复试资料分享
1175. 质数排列
[xi'anjiaotonguniversity] information sharing of the first and second postgraduate entrance examinations
Alibaba cloud database represented by polardb ranks first in the world