给浏览器添加coockie信息
分两种方案,推荐使用第二种方案:
一:
package com.servlet; 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; /** * Servlet implementation class SecondServlet */ //@WebServlet("/SecondServlet") public class Cookies extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Cookies() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //解决乱码问题 response.setContentType("text/html;charset=utf-8"); //本次访问时间 String time = new Date().toLocaleString(); //shez设置时间cookie response.setHeader("Set-cookie", "time ="+time); //获取上次访问时的时间 String oldTime = request.getHeader("Cookie"); //返回浏览器上次访问时间 response.getWriter().write("上次访问的时间为:"+oldTime); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
二:
注:若是使用tomcat8,则这个方法中在cookie中不能有空格,若是有空格则会报错
package com.servlet; import java.io.IOException; import java.text.SimpleDateFormat; 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; /** * Servlet implementation class SecondServlet */ //@WebServlet("/SecondServlet") public class Cookies extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Cookies() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //解决乱码问题 response.setContentType("text/html;charset=utf-8"); //本次访问时间 Date date = new Date(); SimpleDateFormat smf = new SimpleDateFormat("yyyy-MM-dd-hh:mm:ss"); String time = smf.format(date); System.out.println(time); //shez设置时间cookie Cookie cookie = new Cookie("time",time); response.addCookie(cookie);
//做校验的字段
String oldTime = null; //获取上次访问时的时间 Cookie[] cookies = request.getCookies(); if (cookies!=null) { for(Cookie cookie2:cookies){ if ("time".equals(cookie2.getName())) {
//在这里做一个校验,判断cookie里面是否有这个缓存
oldTiem = cookie2.getValue(); //返回浏览器上次访问时间 response.getWriter().write("上次访问的时间为: "+cookie2.getValue()); } } }
//判断字段是否还是为空
if(oldTime==null){
//这里可以看出cookie里面并没有time这个缓存
}
} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }