应用场景:用于自动登录, 浏览记录, 购物车等等。
使用Cookie步骤如下:
-
首先添加Cookie
resp.addCookie(new Cookie("name", "张三"));
-
获取Cookie
Cookie[] cookies = req.getCookies();
-
获取Cookie的name以及value
String name = cookie.getName();
String value = cookie.getValue();
完整代码如下:
public class CookieServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
// 添加cookie
resp.addCookie(new Cookie("name", "张三"));
// 获取cookie, 并将其遍历出来
Cookie[] cookies = req.getCookies();
if(cookies != null) {
for (Cookie cookie : cookies) {
out.write(cookie.getName() + cookie.getValue() + "<br/>");
}
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
小案例:获取上一次的访问时间。
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
Cookie[] cookies = req.getCookies();
if(cookies != null) { // 如果cookie不为空输出上一次访问的时间
for (Cookie cookie : cookies){
if (cookie.getName().equals("currentTime")){ // 获取下面添加的Cookie:currentTime属性
String value = cookie.getValue();
long time = Long.parseLong(value);
Date date = new Date(time);
out.write("上一次访问的时间" + date.toLocaleString());
}
}
}
Cookie cookie = new Cookie("currentTime", System.currentTimeMillis() + "");// 访问时,添加一个访问的当前时间
cookie.setMaxAge(10); // 还有一个设置最大有效时间
resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}