zoukankan      html  css  js  c++  java
  • 小功能:访问页面距上次访问有多久时间

    1、新建一个项目:

     2、在src中建立一个servlet包,包中新建一个servlet

    3、

     4、servlet文件中写代码:

    package LastTimeServlet;
    
    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 {
    
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            Date date=new Date();====================================================================创建一个date对象
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-DD hh:mm:ss");========================用SimpleDateFormat改变日期格式
            String time=sdf.format(date);
            Cookie cookie=new Cookie("lasttime",time);=====================创建Cookie对象,记录当前最新访问时间
            cookie.setMaxAge(60*10);=======================================
            response.addCookie(cookie);
            String lasttime=null;
            Cookie[] cookies=request.getCookies();
            if(cookies!=null){
                for(Cookie c:cookies){
                    if(c.getName().equals("lasttime")){}
                    lasttime=c.getValue();
                }
            }
            //解决中文乱码
            response.setContentType("text/html;charset=utf-8");
            if(lasttime==null){
                response.getWriter().write("你是第一次访问");
            }else{
                response.getWriter().write("距上次访问的时间是"+lasttime);
            }
        }
    
        public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request, response);
        }
    }
  • 相关阅读:
    servlet-01
    JavaWeb——文件上传和下载
    tomcat 7.0.94 下载安装步骤
    java 中 contains() containsKey() containsvalue() 使用
    java通过Runtime和Process类调用外部命令
    build.xml编译报错Specified VM install not found: type Standard VM, name jdk1.7.0_45
    微信小程序样式旋转
    微信小程序轮播图组件 swiper,swiper-item及轮播图片自适应
    HTTPS请求
    ztree插件的使用
  • 原文地址:https://www.cnblogs.com/yang1182/p/9842792.html
Copyright © 2011-2022 走看看