千锋20200420

在千锋“逆战”学习第56天

      每日一句:成功很少是由创意的质量决定的,但它时常由你执行的质量来决定。
      今天学习了Cookie和Session的知识。
      明天继续努力。

思维导图

Cookie案例 记录上一次访问时间

@WebServlet(name = "Demo05Servlet", urlPatterns = "/demo05")
public class Demo05Servlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie[] cookies = req.getCookies();
        Cookie cookie = null;
        if (cookies != null && cookies.length != 0) {
            for (Cookie sonCookie : cookies) {
                if ("lastTime".equals(sonCookie.getName())) {
                    cookie = sonCookie;
                }
            }
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss");
        if (null==cookie) {
            Date currentDate = new Date();
            System.out.println("第一次访问,时间为:" + format.format(currentDate));
            cookie = new Cookie("lastTime", currentDate.getTime() + "");
        } else {
//            System.out.println(cookie.getValue());
            long lastTimeMills = Long.parseLong(cookie.getValue());
            Date lastDate = new Date(lastTimeMills);
            String lastTimeStr = format.format(lastDate);
            System.out.println("上一次访问,时间为:" + lastTimeStr);

            Date currentDate = new Date();
//            cookie.setValue(currentDate.getTime() + " ");
            cookie = new Cookie("lastTime",currentDate.getTime()+"");

        }
        resp.addCookie(cookie);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}

Cookie案例 商品浏览记录

  • books.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>商品页面</title>
</head>
<body>
<h2>商品目录</h2>
<a href="history?id=0">西游记</a><br>
<a href="history?id=1">红楼梦</a><br>
<a href="history?id=2">水浒传</a><br>
<a href="history?id=3">三国志</a>
</body>
</html>
  • HistoryServlet
@WebServlet(name = "HistoryServlet", urlPatterns = "/history")
public class HistoryServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        Cookie cookie = null;
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length != 0) {
            for (Cookie sonCookie : cookies) {
                if ("history".equals(sonCookie.getName())) {
                    cookie = sonCookie;
                }
            }
        }
        if (cookie == null) {
            cookie = new Cookie("history", id);
        } else {
            String historyStr = cookie.getValue();
            if (!historyStr.contains(id)) {
                historyStr += "-" + id;
                cookie.setValue(historyStr);
            } else {
            }
        }
        response.addCookie(cookie);
        response.sendRedirect(request.getContextPath() + File.separator + "show");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
  • ShowHistoryServlet
@WebServlet(name = "ShowHistoryServlet", urlPatterns = "/show")
public class ShowHistoryServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie cookie = null;
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length != 0) {
            for (Cookie sonCookie : cookies) {
                if ("history".equals(sonCookie.getName())) {
                    cookie = sonCookie;
                }
            }
        }
        StringBuffer responseContent = new StringBuffer();
        if (cookie == null) {
            responseContent.append("<font color = 'red'>没有浏览记录</font>");
            responseContent.append("<a href = 'books.html'>浏览商品</a>");
        } else {
            String[] bookNames = {"西游记", "红楼梦", "水浒传", "三国志"};
            String historyStr = cookie.getValue();
            String[] historys = historyStr.split("-");
            responseContent.append("浏览记录如下<br>");
            for (String history : historys) {
                String bookName = bookNames[Integer.parseInt(history)];
                responseContent.append(bookName + "<br>");
            }
        }
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(responseContent.toString());
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
发布了62 篇原创文章 · 获赞 0 · 访问量 1974

猜你喜欢

转载自blog.csdn.net/qq_41841482/article/details/105641181
今日推荐