Thursday, September 8, 2011

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.

package org.kodejava.example.servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HitCounter extends HttpServlet {
    public HitCounter() {
        super();
    }      
   
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {
        updateHitCounter();
        getHitCounterImage(request, response);
    }     
   
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {
        updateHitCounter();
        getHitCounterImage(request, response);
    }

    private void updateHitCounter() {
        Connection connection = getConnection();
        try {
            //
            // 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);
            stmt.executeUpdate();           
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeConnection(connection);
        }
    }
   
    private void getHitCounterImage(HttpServletRequest request,
            HttpServletResponse response) throws IOException {
        Connection connection = getConnection();
        String hits = "";
        try {
            //
            // Get the current hits counter from database.
            //
            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);
        }
       
        //
        // Create an image of our counter to be sent to the browser.
        //
        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);
       
        response.setContentType("image/png");
        OutputStream os = response.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/sampledb", "root", "");
        } 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();           
        }
    }
}

To configure the servlet you'll need to update the web.xml file as follow:

<?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>kodejava-example</display-name>
    <servlet>
        <display-name>HitCounter</display-name>
        <servlet-name>HitCounter</servlet-name>
        <servlet-class>
            org.kodejava.example.servlet.HitCounter
        </servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>HitCounter</servlet-name>
        <url-pattern>/HitCounter</url-pattern>
    </servlet-mapping>
</web-app>
 
To display the hits counter image on the JSP page, create an image tag with the source point to our HitCoutner servlet.
Visited for: <img src="http://localhost:8080/app-name/HitCounter" alt="Hit Counter"/> times.
 
end.............. 


No comments:

Post a Comment