JSP使用application对象实现网站简单计数

描述:JSP使用application对象实现网站简单计数

代码:注意web开发属于多线程操作,所以需要同步

<%@ page language="java" contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>JSP</title>
</head>
<body>
    <%
        // 加入同步方法确保能+1
        synchronized(application) {
            // 获取上一次计数,注意application返回的是Object类型所以需要转换
            String data = (String)application.getAttribute("count");
            if (data == null) {
                application.setAttribute("count", "1");     // 首次访问
            }
            else {
                int i = Integer.parseInt(data);             // 取出上一次数据
                i++;                                        // +1
                application.setAttribute("count", Integer.toString(i)); // 重新写入
            }
        }
    %>
    <%-- 使用EL进行输入,也可以使用application.getAttribute("count")输入 --%>
    <h2>您是第${count}位访客!</h2>
</body>
</html>

缺点:每刷新一次计数值就会+1,所以需要改进

改进:使用session对象的isNew方法判断是否是新用户,如果是则+1,否则则不加

<%@ page language="java" contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>JSP</title>
</head>
<body>
    <%
        // 加入session进行判断是否是新用户
        if (session.isNew()) {
            
            // 加入同步方法确保能+1
            synchronized(application) {
                // 获取上一次计数,注意application返回的是Object类型所以需要转换
                String data = (String)application.getAttribute("count");
                if (data == null) {
                    application.setAttribute("count", "1");     // 首次访问
                }
                else {
                    int i = Integer.parseInt(data);             // 取出上一次数据
                    i++;                                        // +1
                    application.setAttribute("count", Integer.toString(i)); // 重新写入
                }
            }
        }
    %>
    <%-- 使用EL进行输入,也可以使用application.getAttribute("count")输入 --%>
    <h2>您是第${count}位访客!</h2>
</body>
</html>
提示:还是有缺点,因为application对象重启服务器后就会消失,所以如果开发计数器则应该使用保存到文件的方式,当用户访问并且为新用户的时候就+1后再把数据写入文件,这样一来就算换了服务器也不影响之前的访客统计

最后改进:

<%@ page language="java" contentType="text/html" pageEncoding="UTF-8"%>

<%-- 导入包 --%>
<%@ page import="java.io.* "%>
<%@ page import="java.math.* "%>
<%@ page import="java.util.* "%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>JSP</title>
</head>
<body>
    <%-- 数据量很大则可以使用BigInteger --%>
    <%-- 定义全局count用于计数 --%>
    <%!
        BigInteger count = null;
    %>
    <%-- 定义全局方法 --%>
    <%!
        // 定义文件操作方法
        public BigInteger getCount(File file) {
            BigInteger count = null;
            
            // 对文件的操作会有异常,所以需要捕获
            try{
                if (file.exists()) {                          // 必须判断文件是否存在
                    Scanner scan = new Scanner(new FileInputStream(file));
                    // 文件中只有一个数据,所以只需要if而不需要while
                    if (scan.hasNext()) {
                        count = new BigInteger(scan.next());    // 取得数据
                    }
                    scan.close();                               // 关闭输入流
                }
                else{
                    count = new BigInteger("0");            // 新建
                    save(file, count);                      // 保存
                }
            }
            catch(Exception e){
                e.printStackTrace();
            }
            return count;                                       // 返回值
        }

        // 保存文件
        public void save(File file, BigInteger count) {
            try{
                PrintStream out = null;                         // 实例化打印流
                out = new PrintStream(new FileOutputStream(file));
                out.print(count);                             // 写入数据 
                out.close();                                    // 关闭打印流
            }
            catch(Exception e){
                e.printStackTrace();
            }
        }
    %>
    <%
        // 取得虚拟路径真实路径,在根目录下新建count.txt文件
        String path = this.getServletContext().getRealPath("/") + "count.txt";
        File file = new File(path);
        if (session.isNew()) {
            synchronized(this){
                count = getCount(file);                         // 获取值
                count = count.add(new BigInteger("1"));         // 计数值+1
                System.out.println(count);
                save(file, count);                               // 保存
            }
        }
    %>

    <%-- 要考虑count==null的情况 --%>
    <h2>您是第<%=(count==null)? 0 : count%>位访客!</h2>
</body>
</html>
总结:最后改进版可以适用于任何网站,无论数据多大

猜你喜欢

转载自blog.csdn.net/sinat_34104446/article/details/79872987