在servlet中获取cookie [英] Getting cookie in servlet

查看:108
本文介绍了在servlet中获取cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用

Cookie[] cookie = request.getCookies();

cookie 总是 null

所以我从另一个servlet设置它们,它们出现在浏览器首选项中。

So I set them from another servlet and they appear in browser preferences.

Cookie cookie = new Cookie("color", "cyan");
cookie.setMaxAge(24*60*60);
cookie.setPath("/");
response.addCookie(cookie);

我不明白什么是错的?

推荐答案

根据文档 getCookies()返回一个数组,其中包含客户端使用此请求发送的所有Cookie对象。如果没有发送cookie,则此方法返回null。

According to docs getCookies() Returns an array containing all of the Cookie objects the client sent with this request. This method returns null if no cookies were sent.

您是否正确添加了cookie?如果是,您应该能够遍历返回的cookie列表

Did you add the cookie correctly? If yes, you should be able to iterate through the list of cookies returned with

Cookie[] cookies = request.getCookies();

for (int i = 0; i < cookies.length; i++) {
  String name = cookies[i].getName();
  String value = cookies[i].getValue();
}

如果没有...

使用响应对象中的 addCookie(Cookie)方法添加Cookie!

Cookies are added with the addCookie(Cookie) method in the response object!

这篇关于在servlet中获取cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆