今天在写cookie的时候,获取上一次的时间代码如下
//利用cookie,设置用户上一次登录的时间
@WebServlet(name = "LastTimeServlet",urlPatterns="/LastTimeServlet")
public class LastTimeServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 设置编码
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
// 利用java8的time api获取当前时间并格式化
String pattern = "yyyy 年 MM 月 dd 日 H 时 mm 分 ss 秒";
String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern(pattern));
// 设置cookie
Cookie cookie = new Cookie("LastTime",currentTime);
cookie.setMaxAge(60 * 60 * 24);
response.addCookie(cookie);
String LastTime = null;
Cookie[] cookies = request.getCookies();
// 判断是否是第一次登录
if(cookies != null){
for(Cookie cookie1 : cookies){
if(cookie1.getName().equals("LastTime")){
LastTime = cookie1.getValue();
}
}
}
// 如果不是第一次登录,那么响应上次登录的时间
if(LastTime != null){
response.getWriter().write("您上次登录的时间为" + LastTime);
}
// 否则响应第一次登录
else if(LastTime == null){
response.getWriter().write("您是第一次登录");
}
}
然后运行报错在 : response.addCookie(cookie);这一句,说我字符错误,后来google,说我在格式化字符串的时候不能够空格,这样会引起乱码,也就是这一句:
String pattern = “yyyy 年 MM 月 dd 日 H 时 mm 分 ss 秒”;
于是改为了: String pattern = “yyyy-年-MM-月-dd-日-H-时-mm-分-ss-秒”;
运行成功
希望我犯过的错,大家也能犯一遍,这样能记得更牢.