import java.io.IOException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class cookieDemo1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//设置输出格式为utf8
response.setCharacterEncoding("utf8");
response.setContentType("text/html;charset=utf8");
//得到request中的所有cookies
Cookie[] cookies=request.getCookies();
//必须先判断,不然会抛nullPointer异常
if(cookies!=null){
for(Cookie c:cookies){
//找到需要的cookie
if("lastTime".equals(c.getName())){
long time = Long.parseLong(c.getValue());
response.getWriter().write("您上次登录时间是:"+new Date(time).toString());
}
}
}
//重新向浏览器抛出cookie
Cookie cookie = new Cookie("lastTime",System.currentTimeMillis()+"");
//设置cookie的最大存活周期,如果不设置的话,关闭浏览器则cookie消失
cookie.setMaxAge(1*30*24*3600);
//设置访问路径,只有当访问以“javaweb”开头的资源时才发送该cookie,同时该路径是针对浏览器。
cookie.setPath("/javaweb");
//将cookie添加到response中
response.addCookie(cookie);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
10.cookie初步
最新推荐文章于 2014-05-11 11:44:36 发布