一、创建Cookie
public class CookieServlet extends BeanServlet {
protected void createCookie(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.创建Cookie对象
Cookie cookie = new Cookie("key1", "value1");
//2.通知客户端保存Cookie
response.addCookie(cookie);
response.getWriter().write("cookie创建成功");
}
}
二、服务器获取Cookie
protected void getCookie(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie[] cookies = request.getCookies();
// for (Cookie cookie : cookies){
// response.getWriter().write("Cookie[" + cookie.getName() + "=" + cookie.getValue() + "] <br/>");
// }
Cookie cookie = CookieUtils.findCookie("key1", cookies);
if (cookie != null){
response.getWriter().write("Cookie[" + cookie.getName() + "=" + cookie.getValue() + "]");
}
}
三、修改Cookie值
protected void updateCookie(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//方案一
//1.先创建一个要修改的同名的Cookie对象
//2.赋值新的Cookie值
Cookie cookie = new Cookie("key1", "newValue1");
//3.调用response.addCookie(Cookie)通知客户端保存修改
response.addCookie(cookie);
response.getWriter().write("key1的值已修改");
//方案二
//1、先查找到需要修改的 Cookie 对象
Cookie cookie1 = CookieUtils.findCookie("key1", request.getCookies());
if (cookie1 != null){
//2、调用 setValue()方法赋于新的 Cookie 值。
cookie1.setValue("newCookie1");
//3、调用 response.addCookie()通知客户端保存修改
response.addCookie(cookie1);
}
}
四、Cookie生命控制
Cookie
的生命控制指的是如何管理 Cookie
什么时候被销毁
setMaxAge()
//正数,表示在指定的秒数后过期
//负数,表示浏览器一关,Cookie 就会被删除(默认值是-1)
//零,表示马上删除 Cookie
protected void lifeForSomeTime(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie cookie = new Cookie("lifeForTime", "lifeForTime");
cookie.setMaxAge(5); //设置存活时间
response.addCookie(cookie);
}
protected void deleteNow(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie cookie = CookieUtils.findCookie("key1", request.getCookies());
if (cookie != null){
cookie.setMaxAge(0); //设置存活时间
response.addCookie(cookie);
}
response.getWriter().write("key1已经被删除");
}
protected void defaultLife(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie cookie = new Cookie("default", "default");
cookie.setMaxAge(-1); //设置存活时间
response.addCookie(cookie);
}
五、Cookie 有效路径 Path
的设置
Cookie
的 path
属性可以有效的过滤哪些 Cookie
可以发送给服务器,哪些不发。 path
属性是通过请求的地址来进行有效的过滤。
protected void testPath(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie cookie = new Cookie("path1", "path1");
//getContextPath()得到工程名
cookie.setPath(request.getContextPath() + "/abc"); // /工程路径/abc
response.addCookie(cookie);
}