目录
一、cookie的使用
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter out=resp.getWriter();
//Cookie,服务器端从客户端获取
Cookie[] cookies=req.getCookies();//这里返回数组,说明Cookie可能存在多个
//判断cookie是否存在
if(cookies!=null){
//如果存在怎么办
out.write("你上次访问的时间是:");
for (int i=0;i<cookies.length;i++){
Cookie cookie=cookies[i];
//获取cookie的名字
if(cookie.getName().equals("LastLoginTime")){
//获取cookie中的值
Long lastLoginTime=Long.parseLong(cookie.getValue());
Date date=new Date(lastLoginTime);
out.write(date.toLocaleString());
}
}
}else{
out.write("这是你第一次访问本站");
}
//服务端给客户端响应一个cookie
Cookie cookie=new Cookie("LastLoginTime",System.currentTimeMillis()+"");
//cookie有效期为一天
cookie.setMaxAge(24*60*60);
resp.addCookie(cookie);
//解决乱码
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
}
中文的编码与解码:
二、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");
//得到Session
HttpSession session=req.getSession();
//给Session中存东西
session.setAttribute("name",new Person("大表哥",1));
//获取Session的ID
String sessionId=session.getId();
//判断Session是不是新创建
if(session.isNew()){
resp.getWriter().write("session创建成功");
}else{
resp.getWriter().write("session已经存在服务器中,ID:"+sessionId);
}
//Session创建的时候做了什么事情
// Cookie cookie=new Cookie("JSESSIONID",sessionId);
// resp.addCookie(cookie);
}
获取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");
//得到Session
HttpSession session=req.getSession();
Person person=(Person) session.getAttribute("name");
System.out.println(person.toString());
}
注销Session:
手动注销:
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//注销Session
HttpSession session=req.getSession();
session.removeAttribute("name");
//手动注销Session
session.invalidate();
}
自动注销,在web.xml里配置:
<!--设置Session的失效时间-->
<session-config>
<!--15分钟后Session自动失效,以分钟为单位-->
<session-timeout>15</session-timeout>
</session-config>