Java Web 基于Cookie记住已浏览过的书籍

mac2022-06-30  22

思路:

使用Cookie记录已经浏览过的书籍id,再次访问首页的时候,从cookie中读出书籍信息并显示给前端。

项目目录结构:

Book.java文件

package cn.hestyle.web.bean; /** * book的定义 * @author hestyle * */ public class Book { private int id; private String name; private String price; public Book() { } public Book(int id, String name, String price) { this.id = id; this.name = name; this.price = price; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } @Override public String toString() { return "Book [id=" + id + ", name=" + name + ", price=" + price + "]"; } }

DButils.java文件

package cn.hestyle.web.dao; import java.util.ArrayList; import java.util.List; import cn.hestyle.web.bean.Book; public class DButils { private static List<Book> bookList = new ArrayList<Book>(); static { //为了方便演示,所以把书这部分数据全部写死了 bookList.add(new Book(1, "C语言从入门到入土", "9.9")); bookList.add(new Book(2, "C++语言从入门到入土", "19.9")); bookList.add(new Book(3, "Java语言从入门到入土", "20.0")); bookList.add(new Book(4, "Python语言从入门到入土", "20.0")); } /** * 按照id查找book * @param id * @return */ public static Book getBookById(int id) { //遍历bookList,查找id对应的书 for (Book book : bookList) { if (book.getId() == id) { return book; } } return null; } /** * 获取所有的book * @return */ public static List<Book> getAllBooks() { return bookList; } }

BrowseBookServlet.java

package cn.hestyle.web.servlet; import java.io.IOException; 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 cn.hestyle.web.dao.DButils; /** * Servlet implementation class BrowseBookServlet */ @WebServlet("/BrowseBookServlet") public class BrowseBookServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); //获取需要浏览的书籍的id String strId = request.getParameter("id"); int id = Integer.parseInt(strId); response.setHeader("content-type", "text/html;charset=utf-8"); //返回书籍的信息给前端 response.getWriter().write(DButils.getBookById(id).toString()); //从request中读取以浏览过的书籍id序列 String bookIdsStr = ""; Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if ("bookIds".equals(cookie.getName())) { bookIdsStr = cookie.getValue(); break; } } } //由于一本书可能重复浏览,但是不能重复打印,所以需要把之前浏览过的书籍id序列进行去重 //比如bookIdsStr = “1-2-4”,而现在strId = “2”,所以bookIdsStr 需要修改为“1-4”,然后再在尾端加上“-2”,即最终修改为“1-4-2” bookIdsStr = bookIdsStr.replaceAll(strId, ""); if (bookIdsStr.startsWith("-")) { //如果bookIdsStr = “1-2-4”,strId = “1” bookIdsStr = bookIdsStr.substring(1); } else if (bookIdsStr.endsWith("-")) { //如果bookIdsStr = “1-2-4”,strId = “4” bookIdsStr = bookIdsStr.substring(0, bookIdsStr.length() - 1); } else { //如果bookIdsStr = “1-2-4”,strId = “2” bookIdsStr = bookIdsStr.replaceAll("--", "-"); } if (bookIdsStr.length() > 0) { bookIdsStr += "-"; } bookIdsStr += strId; //把修改后的bookIds重新塞给客户端 Cookie cookie = new Cookie("bookIds", bookIdsStr); cookie.setMaxAge(60 * 10); response.addCookie(cookie); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

ShowAllBooks.java

package cn.hestyle.web.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.List; 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 cn.hestyle.web.bean.Book; import cn.hestyle.web.dao.DButils; /** * Servlet implementation class ShowAllBooks */ @WebServlet("/ShowAllBooks") public class ShowAllBooks extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<Book> bookList = DButils.getAllBooks(); //设置字符集为utf-8,否则会出现中文乱码 response.setHeader("content-type", "text/html;charset=utf-8"); PrintWriter writer = response.getWriter(); //先把书籍输出到前端 writer.write("所有书籍:"); for (Book book : bookList) { writer.write("<br><a href = '/Cookie_Test/BrowseBookServlet?id=" + book.getId() + "'> " + book.getName() + "</a>"); } //再把cookie中记录的id序列翻出来,并把id对应的书籍名发给前端 writer.write("<br>浏览过的书籍:"); Cookie[] cookies = request.getCookies(); if (cookies != null) { //遍历cookies,找出浏览过的book的ids字符串 for (Cookie cookie : cookies) { if ("bookIds".equals(cookie.getName())) { String[] ids = cookie.getValue().split("-"); for (String strId : ids) { int id = Integer.parseInt(strId); writer.write("<br>" + DButils.getBookById(id).getName()); } } break; } } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

运行结果:

第一次访问首页: 点击Java语言 重新访问首页 这个小Demo使用用户演示Cookie的作用,大家千万别学我这样编码。。。

最新回复(0)