java web Cookie处理

发布于:2025-07-31 ⋅ 阅读:(22) ⋅ 点赞:(0)

java web 设置cookie
cookie

更改启动端口
更改端口号

// Directory tree (5 levels)
├── src\
│   ├── a.txt
│   └── com\
│       └── zhang\
│           └── ServletContext\
│               ├── cookie\
│               └── servletContext.java
└── web\
    ├── WEB-INF\
    │   ├── c.txt
    │   └── javax.servlet.jar
    ├── b.txt
    ├── index.jsp
    └── login.html

项目基本信息

  • 项目类型 :Java Web应用
    技术栈分析
  • 后端 :Java Servlet
  • 前端 :JSP、HTML
  • 构建工具 :可能使用IntelliJ IDEA自带构建系统
  • 包含用户登录页面(login.html)
  • 可能实现ServletContext相关功能
  • 包含Cookie处理模块(src/com/zhang/ServletContext/cookie目录)

访问
http://localhost:8081/cookieDome1
http://localhost:8081/cookieDome2
http://localhost:8081/cookieTest
http://localhost:8081/cookieTest2
http://localhost:8081/servletContext

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 java.io.IOException;

@WebServlet("/cookieDome1")
public class CookieDome1 extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //    1. 创建Cookie对象,绑定数据
        Cookie cookie = new Cookie("msg", "hello");
        cookie.setMaxAge(300);
        Cookie cookie1 = new Cookie("masg", "123");
        Cookie cookie2 = new Cookie("mmm", "张三");
       cookie2.getPath();

       cookie.setDomain("day21");

        //		2. 发送Cookie对象
        response.addCookie(cookie);
        response.addCookie(cookie1);
        response.addCookie(cookie2);

    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}


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 java.io.IOException;

@WebServlet("/cookieDome2")
public class CookieDome2 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //            3. 获取Cookie,拿到数据
        Cookie[] cookies = request.getCookies();
if(null!=cookies){
        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            String value = cookie.getValue();
            System.out.println(name + ":" + value);
        }
    }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}




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 java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/cookieTest")
public class CookieTest extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //设置相应消息头的格式和编码方式
        response.setContentType("text/html;charset=utf-8");

        //1、获取所有的cookie
        Cookie[] cookies = request.getCookies();
        boolean flag = false;//false代表第一次访问
        if (cookies != null || cookies.length > 0) {
            //2、遍历cookie
            for (Cookie cookie : cookies) {
                //3、获取cookie的名字
                String name = cookie.getName();
                //4、判断是否存在名为:lastTime的cookie
                if (name.equals("lastTime")) {
                    //有该Cookie,不是第一次访问
                    flag = true;//true不是一次访问

                    //响应数据
                    //获取Cookie的value,时间
                    String value = cookie.getValue();
                    //解码
                    System.out.println("解码前是:" + value);
                    value = URLDecoder.decode(value, "utf-8");
                    System.out.println("解码后是:" + value);

                    //获取当前时间的字符串,重新设置Cookie的值,重新发送cookie
                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                    String str_date = sdf.format(date);
                    //URL编码
                    System.out.println("编码前是:" + str_date);
                    str_date = URLEncoder.encode(str_date, "utf-8");
                    System.out.println("编码后是:" + str_date);

                    //设置cookie值 time
                    cookie.setValue(str_date);
                    //设置cookie的存活时间   --- 1个月
                    cookie.setMaxAge(60 * 60 * 24 * 30);
                    //把cookie写回浏览器保存
                    response.addCookie(cookie);

                    response.getWriter().write("<h1>欢迎回来,您上次访问的时间是:" + value + "</h1>");

                    break;
                }
            }
        }

        if (cookies == null || cookies.length == 0 || flag == false) {
            //没有名为lastTime的cookie,是第一次访问

            //获取当前时间的字符串,重新设置Cookie的值,重新发送cookie
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
            String str_date = sdf.format(date);
            //URL编码
            System.out.println("编码前是:" + str_date);
            str_date = URLEncoder.encode(str_date, "utf-8");
            System.out.println("编码后是:" + str_date);
            //新建cookie
            Cookie cookie = new Cookie("lastTime", str_date);
            //设置cookie的存活时间   --- 1个月
            cookie.setMaxAge(60 * 60 * 24 * 30);
            //把cookie写回浏览器保存
            response.addCookie(cookie);

            //响应数据
            response.getWriter().write("<h1>您好,欢迎您首次访问!</h1>");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
}
}




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 java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/cookieTest2")
public class CookieTest2 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置相应消息头的格式和编码方式
        response.setContentType("text/html;charset=utf-8");
        //1、获取所有的cookie
        Cookie[] cookies = request.getCookies();
        boolean flag = false;//false代表第一次访问
        if (cookies != null || cookies.length > 0) {
            //2、遍历cookie
            for (Cookie cookie : cookies) {
                //3、获取cookie的名字
                String name = cookie.getName();
                //4、判断是否存在名为:lastTime的cookie
                if (name.equals("lastTime")) {
                    //有该Cookie,不是第一次访问
                    flag = true;//true不是一次访问

                    //响应数据
                    //获取Cookie的value,时间
                    String value = cookie.getValue();
                    //解码
                    System.out.println("解码前是:" + value);
                    value = URLDecoder.decode(value, "utf-8");
                    System.out.println("解码后是:" + value);

                    //获取当前时间的字符串,重新设置Cookie的值,重新发送cookie
                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                    String str_date = sdf.format(date);
                    //URL编码
                    System.out.println("编码前是:" + str_date);
                    str_date = URLEncoder.encode(str_date, "utf-8");
                    System.out.println("编码后是:" + str_date);

                    //设置cookie值 time
                    cookie.setValue(str_date);
                    //设置cookie的存活时间   --- 1个月
                    cookie.setMaxAge(60 * 60 * 24 * 30);
                    //把cookie写回浏览器保存
                    response.addCookie(cookie);

                    response.getWriter().write("<h1>欢迎回来,您上次访问的时间是:" + value + "</h1>");

                    break;
                }
            }
        }
        if (cookies == null || cookies.length == 0 || flag == false) {
            //没有名为lastTime的cookie,是第一次访问
            //获取当前时间的字符串,重新设置Cookie的值,重新发送cookie
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
            String str_date = sdf.format(date);
            //URL编码
            System.out.println("编码前是:" + str_date);
            str_date = URLEncoder.encode(str_date, "utf-8");
            System.out.println("编码后是:" + str_date);
            //新建cookie
            Cookie cookie = new Cookie("lastTime", str_date);
            //设置cookie的存活时间   --- 1个月
            cookie.setMaxAge(60 * 60 * 24 * 30);
            //把cookie写回浏览器保存
            response.addCookie(cookie);
            //响应数据
            response.getWriter().write("<h1>您好,欢迎您首次访问!</h1>");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}





import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/servletContext")
public class servletContext extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //this.ServletContext();
        ServletContext context = this.getServletContext();


        String b = context.getRealPath("/b.txt");

        //web目录下资源访问
        System.out.println(b);

        String c = context.getRealPath("/WEB-INF/c.txt");//WEB-INF目录下的资源访问
        System.out.println(c);

        String a = context.getRealPath("/WEB-INF/classes/a.txt");//src目录下的资源访问
        System.out.println(a);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}





前端

<%@ page import="java.net.URLDecoder" %>
<%@ page import="java.util.Date" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="java.net.URLEncoder" %><%--
  Created by IntelliJ IDEA.
  User: 86133
  Date: 2020/10/25
  Time: 10:15
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>cookie案例改写</title>
</head>
<body>
<%
    Cookie[] cookies = request.getCookies();
    boolean flag = false;//false代表第一次访问
    if (cookies != null || cookies.length > 0) {
        //2、遍历cookie
        for (Cookie cookie : cookies) {
            //3、获取cookie的名字
            String name = cookie.getName();
            //4、判断是否存在名为:lastTime的cookie
            if (name.equals("lastTime")) {
                //有该Cookie,不是第一次访问
                flag = true;//true不是一次访问

                //响应数据
                //获取Cookie的value,时间
                String value = cookie.getValue();
                //解码
                System.out.println("解码前是:" + value);
                value = URLDecoder.decode(value, "utf-8");
                System.out.println("解码后是:" + value);

                //获取当前时间的字符串,重新设置Cookie的值,重新发送cookie
                Date date = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                String str_date = sdf.format(date);
                //URL编码
                System.out.println("编码前是:" + str_date);
                str_date = URLEncoder.encode(str_date, "utf-8");
                System.out.println("编码后是:" + str_date);

                //设置cookie值 time
                cookie.setValue(str_date);
                //设置cookie的存活时间   --- 1个月
                cookie.setMaxAge(60 * 60 * 24 * 30);
                //把cookie写回浏览器保存
                response.addCookie(cookie);

%>
<h1>欢迎回来,您上次访问的时间是:<%=value%>
</h1>
<%

                break;
            }
        }
    }
    if (cookies == null || cookies.length == 0 || flag == false) {
        //没有名为lastTime的cookie,是第一次访问
        //获取当前时间的字符串,重新设置Cookie的值,重新发送cookie
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        String str_date = sdf.format(date);
        //URL编码
        System.out.println("编码前是:" + str_date);
        str_date = URLEncoder.encode(str_date, "utf-8");
        System.out.println("编码后是:" + str_date);
        //新建cookie
        Cookie cookie = new Cookie("lastTime", str_date);
        //设置cookie的存活时间   --- 1个月
        cookie.setMaxAge(60 * 60 * 24 * 30);
        //把cookie写回浏览器保存
        response.addCookie(cookie);
        //响应数据
%>
<h1>您好,欢迎您首次访问!</h1>
<%
    }
%>

</body>
</html>







<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/servletContext" method="post">
    <button type="submit">访问</button>
</form>


</body>
</html>


网站公告

今日签到

点亮在社区的每一天
去签到