zoukankan      html  css  js  c++  java
  • 通过Cookie统计上次网页访问时间

    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;


    public class LastTimeServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
    Cookie[] cookies = req.getCookies();//拿到Cookies集合
    String msg="";
    Cookie cook=null;
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String newDate = sdf.format(date);//将当前的时间格式化
    for(Cookie c:cookies){
    String name = c.getName();

    //非首次访问
    if("lastTime".equals(name)){
    cook=c;
    msg=c.getValue();//拿到cook里的日期
    c.setValue(newDate);//将当前访问日期设置进去
    }
    }

    //首次访问
    if("".equals(msg)){
    msg="首次访问";
    cook=new Cookie("lastTime",newDate);//将当前时间是指进去
    }
    cook.setMaxAge(199999999);
    resp.addCookie(cook);//将cook放到响应对象里
    req.setAttribute("msg", msg);
    req.getRequestDispatcher("/success.jsp").forward(req, resp);//转发
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
    doGet(req, resp);
    }

    }

    web页面

      index页面(为了方便只写bodyti,请自行补全)

    <body>
    <form action="/JavaMailTest/lastTime" method="post">
    <input type="submit" value="submit"/>
    </form>
    </body>

      success页面

    <body>
    上次访问的时间是:<%=request.getAttribute("msg") %>
    </body>

    web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
    <display-name>JavaMailTest</display-name>
    <servlet>
    <servlet-name>LastTimeServlet</servlet-name>
    <servlet-class>LastTimeServlet</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>LastTimeServlet</servlet-name>
    <url-pattern>/lastTime</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    </web-app>

     

  • 相关阅读:
    lintcode491 回文数
    lintcode514 栅栏染色
    lintcode433 岛屿的个数
    lintcode142 O(1)时间检测2的幂次
    lintcode166 链表倒数第n个节点
    lintcode539 移动零
    lintcode: Check Sum of Square Numbers
    lintcode: Missing String
    lintcode 二叉树的锯齿形层次遍历
    Mysql 游标的定义与使用方式
  • 原文地址:https://www.cnblogs.com/xyzq/p/5708403.html
Copyright © 2011-2022 走看看