当前位置:网站首页>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
边栏推荐
- Oceanbase installation Yum source configuration error and Solutions
- wallys/600VX – 2×2 MIMO 802.11ac Mini PCIe Wi-Fi Module, Dual Band, 2,4GHz / 5GHz QCA 9880
- 对象映射 - Mapping.Mapster
- 数据库 自动增长
- QT embeds the sub QT program window into the current program
- Livedata source code appreciation III - frequently asked questions
- CVPR 2022 | 大幅减少零样本学习所需人工标注,马普所和北邮提出富含视觉信息的类别语义嵌入...
- Le talent scientifique 丨 dessins animés qu'est - ce qu'erdma?
- 缓存雪崩和缓存穿透解决方案
- 国产数据库的黄金周期要来了吗?
猜你喜欢

【IC5000教程】-01-使用daqIDEA图形化debug调试C代码

Kotlin 协程调度切换线程是时候解开谜团了

Introduction to China Mobile oneos development board

R language view version R package view version

他是上海两大产业的第一功臣,却在遗憾中默默离世

Boost研究:Boost Log

科普達人丨漫畫圖解什麼是eRDMA?

"War" caused by a bottle of water

Alibaba cloud database represented by polardb ranks first in the world

Oracle NetSuite 助力 TCM Bio,洞悉数据变化,让业务发展更灵活
随机推荐
100 important knowledge points that SQL must master: Combined Query
R language de duplication operation unique duplicate filter
Evaluation of IP location query interface Ⅲ
限时预约|6 月 Apache Pulsar 中文开发者与用户组会议
Compression state DP bit operation
阿里云李飞飞:中国云数据库在很多主流技术创新上已经领先国外
Summer vacation study record
EMC surge
10 days to learn how to flutter Day10 flutter play animation and packaging
koa - 洋葱模型浅析
100 important knowledge points that SQL must master: using subquery
Train an image classifier demo in pytorch [learning notes]
Multiparty Cardinality Testing for Threshold Private Set-2021:解读
In depth analysis of Apache bookkeeper series: Part 4 - back pressure
Speech signal processing - Fundamentals (V): Fourier transform
100 important knowledge points that SQL must master: creating and manipulating tables
“新数科技”完成数千万元A+轮融资,造一体化智能数据库云管理平台
一个人就是一本书
1175. prime permutation
Mathematics (fast power)