Friday, September 19, 2014

Java EE Page View Servlet : Simple app analytics

For this post I'm going to show how you can provide a simple page view recorder using a couple lines of html and java. Sometimes you want to record simple analytics about page views in your jsp/servlet based java web application. You could always attach Google Analytics but you may have an internal application which you do not want to tell Google about. In that case here is some sample code to allow you to do this easily yourself.

* Note: I get my user information from a session variable called user as an example.


In your JSP or HTML page:

<img src="/yourappscontextpath/PageView.servlet?page=<%=request.getRequestURI().toString()%>" style="display: none;" />

* Note: Replace the text yourappscontextpath with your actual applications context path.


Create a new Servlet called PageViewServlet and set up the servlet mapping to point to PageView.servlet:

In the doGet method add the following code:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
User user = (User) request.getSession().getAttribute("user");
String page = request.getParameter("page");
// Add your own code here to save the user and page to the database or to a file.
}

Now you can view each time a user accesses a certain page in your application using this simple process. Enjoy!

No comments:

Post a Comment