Servlet案例之统计访问量与获取类路径下资源

来源:互联网 发布:linux eagle监控软件 编辑:程序博客网 时间:2024/05/22 21:51

一个项目中所有的资源被访问都要对访问量进行累加
创建一个int类型的变量,用来保存访问量,然后把它保存到ServletContext的域中,这样可以保证所有Servlet都可以访问到

这个访问量是整个项目共享的,需要使用ServletContext来保存访问量

1、最初不设置访问量相关属性2、当本站第一次被访问时,创建一个变量,设置其值为1,保存到ServletContext中3、当以后的访问,就可以从ServletContext中获取这个变量,然后在其基础上加1

思路

第一次访问:调用ServletContext的setAttribute()传递一个属性,名为count,值为1之后的访问,调用ServletContext的getAttribute()方法获取原来的访问量,给访问量加1,再调用ServletContext的setAttribute()方法完成设置。

servlet内代码

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        //1.获取ServletContext对象        ServletContext application = this.getServletContext();        //2.获取count对象        Integer count = (Integer)application.getAttribute("count");        if(count==null){            application.setAttribute("count",1);        }        else{            application.setAttribute("count",count+1);        }        //向浏览器输出        Integer count1 = (Integer)application.getAttribute("count");        PrintWriter pw = response.getWriter();        pw.print("<h1>"+count1+"</h1>");    }

获取类路径下资源

获取类路径资源,类路径对一个JavaWeb项目而言,就是/WEB-INF/calsss 和/WEB-INF/lib/每个jar包
        //相对/classes        ClassLoader c1 = this.getClass().getClassLoader();        InputStream input = c1.getResourceAsStream("web/servlet/a.txt");        //相对当前.class        Class c = this.getClass();        InputStream input1 = c.getResourceAsStream("a.txt");        //相对/classes        InputStream input2 = c.getResourceAsStream("/a.txt");

在Class下
不加斜杠相当于在.class文件路径内
加斜杠相当于在/classes文件路径内
在ClassLoader下相当于在/classes文件路径内

阅读全文
0 0
原创粉丝点击