[size=15.0000pt]一,什么是cookie 浏览器端的会话技术,它通过在浏览器中记录一些服务器传递过来的数据,解决会话从什么时候开始,到什么时候结束 二,cookie的应用,浏览器显示日期时间及控制台获取输出cookie(解决cookie值中不能使用分号(;)、逗号(,)、等号(=)以及空格的问题)使用idea创建web项目,创建TimeServlet @WebServlet(name = "TimeServlet", urlPatterns = "/TimeServlet")
public class TimeServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String day = new SimpleDateFormat("yyyy年MM月dd日 ;,= hh时mm分ss秒").format(new Date());
String encode = URLEncoder.encode(day, "utf-8");//对非英文字符编码
Cookie c = new Cookie("time",encode);//创建cookie
c.setMaxAge(60*60*24);//设置存活时间一天
response.addCookie(c);//将cookie添加到response对象
//第二次访问获取cookie
Cookie[] cookies = request.getCookies();
if(cookies!=null){
for (Cookie cc:cookies){
if("time".equals(cc.getName())){
System.out.println(cc.getValue());
//解码
String decode = URLDecoder.decode(cc.getValue(), "utf-8");
response.setContentType("text/html;charset=utf-8");
response.getWriter().write(decode);
}
}
}
}
} 启动Tomcat,并访问,输出日期时间
|