- Initialize a global variable in init() method.
- Increase global variable every time either doGet() or doPost() method is called.
- If required, you can use a database table to store the value of global variable in destroy() method. This value can be read inside init() method when servlet would be initialized next time. This step is optional.
- If you want to count only unique page hits with-in a session then you can use isNew() method to check if same page already have been hit with-in that session. This step is optional.
- You can display value of the global counter to show total number of hits on your web site. This step is also optional.
CounterServlet.java
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class CounterServlet extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(true); response.setContentType("text/html"); PrintWriter out = response.getWriter(); Integer count = new Integer(0); String head; if (session.isNew()) { head = "This is the New Session"; } else { head = "This is the old Session"; Integer oldcount =(Integer)session.getValue("count"); if (oldcount != null) { count = new Integer(oldcount.intValue() + 1); } } session.putValue("count", count); out.println("<HTML><BODY BGCOLOR="#FDF5E6">n" + "<H2 ALIGN="CENTER">" + head + "</H2>n" + "<TABLE BORDER=1 ALIGN=CENTER>n" + "<TR BGCOLOR="#FFAD00">n" +" <TH>Information Type<TH>Session Countn" +"<TR>n" +" <TD>Total Session Accessesn" + "<TD>" + count + "n" + "</TABLE>n" +"</BODY></HTML>" ); } }
Mapping of Servlet (“CounterServlet.java”) in web.xml file
<servlet> <servlet-name>CounterServlet</servlet-name> <servlet-class>CounterServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>CounterServlet</servlet-name> <url-pattern>/CounterServlet</url-pattern> </servlet-mapping>
Running the servlet by this url:
http://localhost:8080/CounterServlet
displays the figure below:
When servlet is hit six times by the user the counter value will be increased by six as shown in figure below:
- Java Servlets Overview
- Servlet Life Cycle
- Servlet Example
- Difference between ServletConfig and ServletContext
- Difference between GenericServlet and HttpServlet
- What is web application?
- Advantages of Servlets over CGI
- GenericServlet Example
- RequestDispatcher Example
- ServletConfig
- ServletContext
- Servlet Filter Example
- Database Access Example using Sevlet
- File Uploading Example using Servlet