How do I create a hit counter servlet?

Here we have a simple example of creating a hit counter using servlet. The servlet updates the hits counter every time a page is visited and display the number of hits as an image. The image is generated at runtime using Java’s Graphic2D and ImageIO class.

To store the number of visit data we create a table hits with a single field called counter and set the initial value of the counter to zero. Below is the HitCounterServlet servlet code.

package org.kodejava.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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.sql.*;

@WebServlet(name = "HitCounterServlet", urlPatterns = "/hitcounter")
public class HitCounterServlet extends HttpServlet {
    private static final String URL = "jdbc:mysql://localhost/kodejava";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "";

    public void init() throws ServletException {
        try {
        } catch (ClassNotFoundException e) {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        getHitCounterImage(request, response);

    private void updateHitCounter() {
        try (Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD)) {
            // Update the hits counter table by incrementing the
            // counter every time a user hits our page.
            String sql = "UPDATE hits SET counter = counter + 1";
            PreparedStatement stmt = connection.prepareStatement(sql);
        } catch (SQLException e) {

    private void getHitCounterImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String hits = "";
        try (Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD)) {
            // Get the current hits counter from database.
            String sql = "SELECT counter FROM hits";
            PreparedStatement stmt = connection.prepareStatement(sql);
            ResultSet rs = stmt.executeQuery();
            while ( {
                hits = rs.getString("counter");
        } catch (SQLException e) {

        // Create an image of our counter to be sent to the browser.
        BufferedImage buffer = new BufferedImage(50, 30, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = buffer.createGraphics();
        g.setFont(new Font("Monospaced", Font.PLAIN, 14));
        g.fillRect(0, 0, 50, 30);
        g.drawString(hits, 10, 20);

        OutputStream os = response.getOutputStream();
        ImageIO.write(buffer, "png", os);

To display the hits counter image on the JSP page, create an img tag with the source (src) point to our HitCounterServlet servlet url.

Visited for: <img src="http://localhost:8080/hitcounter" alt="Hit Counter"/> times.

Maven dependencies


Maven Central Maven Central

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.