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>

     

  • 相关阅读:
    IIS运行asp程序出现The requested resource is in use 和 安装.net 2.0 后运行2.0程序出现 Failed to access IIS metabase 错误的解决
    动态sql语句基本语法
    屏蔽浏览器关闭按钮及ALT+F4 快捷键
    [转]如何进行.NET高效开发
    HttpRuntime.Cache 与HttpContext.Current.Cache的疑问
    我搜集的关于工作流方面的技术文章
    [转]输入框自动完成,模仿IE的,支持FireFox
    javascript 的面向对象特性参考
    定义局部变量时,字符串不能超过8000的方法
    世联地产软件工程师笔试试题
  • 原文地址:https://www.cnblogs.com/xyzq/p/5708403.html
Copyright © 2011-2022 走看看