您的位置:首页 > 运维架构 > 网站架构

javaWeb-02-cookie案例-显示用户上次访问网站的时间

2013-02-16 10:47 786 查看
02-cookie案例-显示用户上次访问网站的时间

javax.servlet.http.Cookie类用于创建一个Cookie,

response接口也中定义了一个addCookie方法,它用于在其响应头中增加一个相应的Set-Cookie头字段。

同样,request接口中也定义了一个getCookies方法,它用于获取客户端提交的Cookie。Cookie类的方法:


public Cookie(String name,String value)
setValue与getValue方法
setMaxAge与getMaxAge方法
setPath与getPath方法
setDomain与getDomain方法
getName方法

用户上次访问网站的时间

public class CookieDemo2 extends HttpServlet {
			private static final long serialVersionUID = 1L;
			//02-cookie案例-显示用户上次访问网站的时间
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
				response.setCharacterEncoding("UTF-8");
				response.setContentType("text/html;charset=UTF-8");
				PrintWriter out = response.getWriter();
				out.print("您上次访问的时间是:");
				//获得用户的时间cookie
				Cookie cookies[] = request.getCookies();
				for(int i = 0;cookies != null && i < cookies.length;i++){
					if(cookies[i].getName().equals("lastAccessTime")){
						long cookieValue = Long.parseLong(cookies[i].getValue());
						Date date = new Date(cookieValue);
						out.print(date.toLocaleString());
					}
				}
		//给客户送回最新的访问时间
				Cookie cookie = new Cookie("lastAccessTime",System.currentTimeMillis()+"");
				cookie.setMaxAge(3600);//设置cookie的时间
				cookie.setPath("/day07");//设置给客户端返回cookie的目录
				response.addCookie(cookie);
				
			}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
				// TODO Auto-generated method stub
			}

		}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: