ITPub博客

首页 > 应用开发 > Java > java中cookie操作详细

java中cookie操作详细

Java 作者:WOSHI太阳 时间:2021-01-26 22:35:01 0 删除 编辑

1.设置Cookie

 代码如下  
Cookie cookie = new Cookie("key", "value");

  cookie.setMaxAge(60);
 

  设置60秒生存期,如果设置为负值的话,则为 浏览器进程Cookie( 内存中保存),关闭浏览器就失效。

 代码如下

  cookie.setPath("/test/test2");
 

  设置Cookie路径,不设置的话为当前路径(对于Servlet来说为request.getContextPath() + web.xml里配置的该Servlet的url-pattern路径部分) 。

 代码如下  
response.addCookie(cookie);
 

  2.读取Cookie

  该方法可以读取当前路径以及“直接父路径”的所有Cookie对象,如果没有任何Cookie的话,则返回null。

 

 代码如下

 Cookie[] cookies = request.getCookies(); 

  3.删除Cookie

 代码如下  
Cookie cookie = new Cookie("key", null);

  cookie.setMaxAge(0);
 

  设置为0为立即删除该Cookie;

 代码如下  
cookie.setPath("/test/test2");
 

  删除指定路径上的Cookie,不设置该路径,默认为删除当前路径Cookie;

  

 代码如下 response.addCookie(cookie); 

下面用一个完整的实例来说明

 

 代码如下  
<%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.3lian.com/">
<html xmlns="http://www.3lian.com/">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>

<body>
<%
    String username = null;
    Cookie[] cookies = request.getCookies();
    if(cookies!=null)
    {
        for(int i=0;i<cookies.length;i++)
        {
            if("cookies_user".equals(cookies[i].getName()))
            {
                username = cookies[i].getValue();//cookies_user}
        }
        
        if("onepc".equals(username))
        {
            out.println("Hello");
        }else
        {
        %>
        
<table width="302" border="1">


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69994010/viewspace-2753476/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: 没有了~
请登录后发表评论 登录
全部评论

注册时间:2021-01-26

  • 博文量
    12
  • 访问量
    7189