cookie應用之顯示當前時間,上次時間
阿新 • • 發佈:2019-01-25
package com.neuedu.servlet; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; importjava.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by Administrator on 2016/11/28 0028. */ @WebServlet(name = "timeServlet",urlPatterns = "/lasttime") public class timeServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); //取得當前時間字串 SimpleDateFormat sdf=newSimpleDateFormat("yyyy-MM-dd hh:mm:ss"); String curdate=sdf.format(new Date()); PrintWriter pw=response.getWriter(); Cookie [] cookies=request.getCookies(); String strtime=""; boolean isfirstvisit=true;//假定當前是第一次訪問 if(cookies!=null){ for(Cookie c:cookies){ //看cookie中是否含有名稱是lasttime的cookie,如果有,不是第一次訪問(之前設定過這個cookie了) //如果迴圈一圈都沒有發現名稱是lasttime的cookie,說明是第一次訪問 if("lasttime".equals(c.getName())){ isfirstvisit=false; strtime=c.getValue(); } } } //將當前時間儲存到cookie中 Cookie c=new Cookie("lasttime",curdate); response.addCookie(c); if(!isfirstvisit){ pw.print("上次訪問時間是"+curdate); pw.print("當前時間是"+strtime); } else { pw.print("當前時間是"+curdate); } } }