Uses:
we can get the how many numbers of users are visited our site and how many times using ServletContextListener interface.
-> used for finding the total no.of page views or likes
we can get the how many numbers of users are visited our site and how many times using ServletContextListener interface.
ServletContextListener interface contain two imporatant
methods
1
contextInitialized(ServletContextEvent)
contextDestroyed(ServletContextEvent)
Step 1: Create a database table
Create table count(hitcount int(11));
Insert into hitcount values(0);
Step 2: Develop a Listener class
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyCounter implements
ServletContextListener
{
ServletContext ctx;
Connection con;
Statement s;
PreparedStatement ps;
ResultSet rs;
int
count;
HttpServletRequest request;
HttpServletResponse response;
public
void contextInitialized(ServletContextEvent sce) {
try{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/ashok","root","root");
s=con.createStatement();
rs=s.executeQuery("select hitcount from counter");
while(rs.next())
{
count=rs.getInt(1);
}
ctx=sce.getServletContext();
ctx.setAttribute("pcount", count);
ctx.getRequestDispatcher("index.jsp").forward(request,response);
}catch(Exception e){
e.printStackTrace();
}
public
void contextDestroyed(ServletContextEvent sce) {
try
{
ctx=sce.getServletContext();
count=(Integer)ctx.getAttribute("pcount");
ps=con.prepareStatement("update counter set
hitcount='"+count+"'");
ps.executeUpdate();
}
catch(Exception e){ e.printStackTrace(); }
}
}
<listener>
<description>ServletContextListener</description>
<listener-class>MyCounter</listener-class>
</listener>
Step 3: Develop a corresponding jsp
<html>
<head>
<title>Home Page</title>
</head>
<body>
<% Integer
count=(Integer)application.getAttribute("pcount"); %>
<h1>Hello Viewer</h1>
<div> Page Views are ::::<%= count++ %>
</div>
<%
application.setAttribute("pcount", count); %>
</body>
</html>
Result :
0 comments:
Post a Comment