cookie
/保存用户上一次访问的时间
public class CookieDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setHeader("Content-Type","text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
//cookie,服务端从客户端获取
Cookie[] cookies = req.getCookies();
if (cookies != null) {
out.write("上一次访问");
for (Cookie cookie : cookies) {
if("time".equals(cookie.getName())) {
// cookie.getValue();
Date date = new Date(Long.parseLong(cookie.getValue()));
SimpleDateFormat sdf = new SimpleDateFormat();
out.write(sdf.format(date));
}
}
} else {
out.write("第一次访问");
}
Cookie cookie = new Cookie("time", System.currentTimeMillis() + "");
resp.addCookie(cookie);
}
Session
和cookie区别:
- cookie是把用户的数据写给用户的浏览器,浏览器可以保存
- session是用户的数据写到用户独占的session中, 服务器端保存
- session由服务创建
建议使用场景:
- 保存一个用户登录信息
- 购物车信息
- 在整个网站中经常使用的数据,保存在session中
@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");
//
HttpSession session = req.getSession();
//set
session.setAttribute("name","zzz");
//get ID
String id = session.getId();
//判断是否新创建
if(session.isNew()) {
resp.getWriter().write("session创建成功,ID 为" + id);
}else {
resp.getWriter().write("session已经存在,ID 为" + id);
}
}
得到session
@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");
//
HttpSession session = req.getSession();
String name =(String) session.getAttribute("name");
System.out.println("name" + name);
}