Servlet如何创建计数器?

在这里,我们有一个使用servlet创建计数器的简单示例。每次访问页面时,该servlet都会更新点击计数器,并以图像的形式显示点击数。该图像是在运行时使用JavaGraphic2D和ImageIO类生成的。

要存储点击数据,请创建一个表,hits其中包含一个名为的字段counter,并将计数器的初始值设置为零。下面是HitCounterServletservlet代码。

package org.nhooo.example.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.*;

public class HitCounterServlet extends HttpServlet {
    public HitCounterServlet() {
        super();
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        updateHitCounter();
        getHitCounterImage(req, res);
    }

    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response)
            throws ServletException, IOException {
        updateHitCounter();
        getHitCounterImage(request, response);
    }

    private void updateHitCounter() {
        Connection connection = getConnection();
        try {
            // 通过增加点击数来更新点击计数器表
            // 用户每次访问我们的页面时都进行计数。
            String sql = "UPDATE hits SET counter = counter + 1";
            PreparedStatement stmt = connection.prepareStatement(sql);
            stmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeConnection(connection);
        }
    }

    private void getHitCounterImage(HttpServletRequest req,
                                    HttpServletResponse res)
            throws IOException {
        Connection connection = getConnection();
        String hits = "";
        try {
            // 从数据库获取当前命中计数器。
            String sql = "SELECT counter FROM hits";
            PreparedStatement stmt = connection.prepareStatement(sql);
            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                hits = rs.getString("counter");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeConnection(connection);
        }

        // 创建要发送到浏览器的柜台图片。
        BufferedImage buffer = new BufferedImage(50, 20, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = buffer.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        g.setFont(new Font("Monospaced", Font.PLAIN, 14));
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, 50, 20);
        g.setColor(Color.BLACK);
        g.drawString(hits, 0, 20);

        res.setContentType("image/png");
        OutputStream os = res.getOutputStream();
        ImageIO.write(buffer, "png", os);
        os.close();
    }

    private Connection getConnection() {
        Connection connection = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(
                    "jdbc:mysql://localhost/nhooo", "nhooo", "nhooo123");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }

    private void closeConnection(Connection connection) {
        try {
            if (connection != null && !connection.isClosed()) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

要配置servlet,您需要web.xml按照以下步骤更新文件:

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>nhooo-example</display-name>
    <servlet>
        <display-name>HitCounter</display-name>
        <servlet-name>HitCounter</servlet-name>
        <servlet-class>
            org.nhooo.example.servlet.HitCounterServlet
        </servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>HitCounter</servlet-name>
        <url-pattern>/HitCounter</url-pattern>
    </servlet-mapping>
</web-app>

要在JSP页面上显示点击数计数器图片,请创建带有源点指向我们HitCoutnerServletservlet的图片标签。

Visited for: <img src="http://localhost:8080/app-name/HitCounter" alt="Hit Counter"/> times.