response.addCookie(cookie)无效

本文介绍如何设置Cookie的访问路径和域名等属性,并展示了具体的代码实现。通过这些设置,可以更好地控制Cookie的作用范围。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Cookie cookie = new Cookie("access", access);
 //cookie.setMaxAge(3600); 让cookie跟session时间走
 cookie.setDomain("www.ipzixun.net");
 cookie.setPath("/");

 response.addCookie(cookie);

如上,注意设置domain和path

欢迎访问我的技术群425783133

为什么我可以在代码中跳转到cookie页面,但是无法在浏览器跳转? package org.example; import javax.servlet.annotation.WebServlet; import javax.servlet.http.*; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; import java.util.UUID; @WebServlet("/cookie") //注解方式,无需在web.xml配置ServLet public class CookieSessionServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { // 设置响应类型 response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); // 1. 读取所有Cookie Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { System.out.println("Cookie: " + cookie.getName() + " = " + cookie.getValue()); } } else { System.out.println("Cookies is empty! "); // 2. 创建新Cookie Cookie myCookie = new Cookie("myCookie", UUID.randomUUID().toString()); myCookie.setMaxAge(7 * 24 * 60 * 60); // 7天有效期 response.addCookie(myCookie); } // 3. 操作Session HttpSession session = request.getSession(false); if(session == null) { System.out.println("Session is empty! I will create a new one. "); session = request.getSession(true); // 获取session session.setAttribute("loginTime", new Date()); } else { System.out.println("Session ID: " + session.getId()); } // 输出信息 out.println("<h1>登录成功</h1>"); } } <!DOCTYPE html> <html> <head> <title>首页</title> </head> <body> <h1>欢迎访问!</h1> <a href="/cookie">测试Cookie</a> </body> </html>
最新发布
08-13
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值