JavaWeb servlet 使用Cookie记录用户访问次数
2021-9-26
·
hexer

讲解

创建CookieLoginTime继承HttpServlet

重写doGet,doPost方法就不再赘述,我们的侧重点是在使用Cookie记录信息 Cookie是由一个个的键值对组成,就类似哈希,或者数组(一个下标对一个数据) Cookie无法直接搜索到name就直接删除,操作Cookie只是添加和修改倒是问题不大

我先简单写一下doget和dopost

然后去web.xml里定义映射

然后开始写doget的细节


几个问题:1乱码,2Cookie的value增加 乱码在前面加

resp.setHeader("Content-Type", "text/html;charset=UTF-8");
req.setCharacterEncoding("UTF-8");

若果不设置Cookie的path,则名字相同的Cookie视为相同的Cookie,后面的覆盖前面的,注意:大小写敏感 参考:https://blog.csdn.net/czh500/article/details/80420061

所以我们可以用这个特点获取然后添加Cookie

在这里插入图片描述 在这里插入图片描述

CookieLoginTime类

package top.sehnsucht;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description:
 * @Author: Cai
 * @CreateTime: 2021/9/26
 * ~~(^_^)~~
 */

public class CookieLoginTime extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setHeader("Content-Type", "text/html;charset=UTF-8");
        req.setCharacterEncoding("UTF-8");
        Cookie[] cookies = req.getCookies();

        for (Cookie cookie : cookies) {
            if ("time".equals(cookie.getName())) {
                int time = Integer.parseInt(cookie.getValue()) + 1;
                resp.getWriter().println("这是您第" + time + "次访问本站");
                resp.addCookie(new Cookie(cookie.getName(), Integer.toString(time)));
                return;
            }
        }
        Cookie cookie = new Cookie("time", "1");
        resp.getWriter().println("这是您第" + cookie.getValue() + "次访问本站");
        resp.addCookie(cookie);
    }

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


web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
	http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

  <display-name>Archetype Created Web Application</display-name>
  <servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>top.sehnsucht.HelloServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/hello</url-pattern>
  </servlet-mapping>

  <servlet>
    <servlet-name>loginTime</servlet-name>
    <servlet-class>top.sehnsucht.CookieLoginTime</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>loginTime</servlet-name>
    <url-pattern>/time</url-pattern>
  </servlet-mapping>

</web-app>