在servlet中给访问者加入cookie的方法
Cookie cookie = new Cookie("username", name);
cookie.setMaxAge(24*3600);
response.addCookie(cookie);
在servlet中得到cookie的方法
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
Cookie[] cookies = request.getCookies();
for(Cookie cookie:cookies){
System.out.println(cookie.getName()+":"+cookie.getValue());
}
}
控制台中可以看到
JSESSIONID:1025111EA7268F96AF27DFCEC7DC136F
Cookie cookie = new Cookie("username", name);
cookie.setMaxAge(24*3600);
response.addCookie(cookie);
在servlet中得到cookie的方法
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
Cookie[] cookies = request.getCookies();
for(Cookie cookie:cookies){
System.out.println(cookie.getName()+":"+cookie.getValue());
}
}
控制台中可以看到
JSESSIONID:1025111EA7268F96AF27DFCEC7DC136F
本文介绍了在Servlet中如何为访问者设置Cookie以及如何获取Cookie。通过示例代码展示了创建Cookie、设置过期时间并添加到响应对象的过程,同时也展示了如何从请求对象中读取Cookie。
1421

被折叠的 条评论
为什么被折叠?



