【web后端(八)】jsp、servlet_会话管理_cookie

 cookie的特性:

当我们再向相同域的相同目录的相同组件发出请求,这段文本还会提交。也就是说,只要是相同域下,都会自动提交,默认如此。 如果域名变了,就不会给发送了。 

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;

//这里可以直接在urlPatterns里配置多个路径
@WebServlet(name = "CookieServlet",urlPatterns = "/abc/bbc/cookie")
public class CookieServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //cookie是服务器写到客户端的一小段文本,
        //是服务器存到客户端的数据,
        //所以安全度不是很高。
        //cookie只能存文本
        //http协议只支持文本
        Cookie c1 = new Cookie("name", "zhangssan");
        c1.setComment("this is a uesr name!");
        c1.setMaxAge(2 * 24 * 60 * 60);
//        c1.setDomain("www.sina.com");
        c1.setPath("/abc/abc");
        c1.setSecure(true);
        c1.setVersion(1);
        response.addCookie(c1);
        Cookie c2 = new Cookie("sex", "M");
        Cookie c3 = new Cookie("passwo" + "rd", "1111");
        //下面的两种方法是在响应头里添加了属性
//        response.setHeader("set-name","name=zhnagsan" );
        //这里我们发的cookie实际上是临时cookie,
        //是存在缓存里头的。
        //只有持久cookie能存成文件,
        //而且不好找。
        //因为这个文本存的地方是由浏览器来决定的。
        response.addCookie(c2);
        response.addCookie(c3);

    }
}
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(name = "Cookie1Servlet",urlPatterns = "/cookie1")
public class Cookie1Servlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //cookie也可以像url重写和隐藏域一样,做同样的事情。
        //request自动给分割数组对象
        Cookie[] cs = request.getCookies();
        for (Cookie c : cs) {
            //取cookie对象时,用键和值的方法取。
            System.out.println(c.getName() + ":" + c.getValue());
            System.out.println(c.getComment());
        }
    }
}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_临渔_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值