Many
times you would be interested in knowing total number of hits of your site,
time of hitting, and number of users currently using your site.
This post is
about creating a hit counter that counts number of site visit. There are
various ways for creating hit counter in servlet but here we have implemented
hit counter using ServletContextListener. ServletContextListener is a listener interface that
gets notified when the context is initialized and destroyed.
index.html
<body>
<form name="loginForm"
method="get" action="LoginServlet">
Username<input
type="text" name="txtname"
size="20"><br>
Password<input
type="password" name="txtpass"
size="20"><br>
<input type="submit"
value="Login">
</form>
</body>
LoginServlet
package
nkpack;
import
java.util.Date;
import
java.io.IOException;
import
java.io.PrintWriter;
import
java.sql.*;
import
java.util.logging.Level;
import
java.util.logging.Logger;
import
javax.servlet.RequestDispatcher;
import
javax.servlet.ServletConfig;
import
javax.servlet.ServletException;
import
javax.servlet.http.HttpServlet;
import
javax.servlet.http.HttpServletRequest;
import
javax.servlet.http.HttpServletResponse;
import
javax.servlet.http.HttpSession;
/**
*
* @author Navindra Jha
*/
public
class LoginServlet extends HttpServlet {
protected void
processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
Connection con=null;
try {
/* TODO output your page here*/
String
name=request.getParameter("txtname");
String
pass=request.getParameter("txtpass");
ServletConfig
config=getServletConfig();
String
dclass=config.getInitParameter("driverClass");
String cstr=config.getInitParameter("conStr");
Class.forName(dclass);
con=DriverManager.getConnection(cstr,"root","");
PreparedStatement
pstmt=con.prepareStatement("select * from login where uname=? and
upass=?");
pstmt.setString(1, name);
pstmt.setString(2, pass);
ResultSet
rset=pstmt.executeQuery();
out.println("<body>");
if(rset.next())
{
Date d=new Date();
String
time=d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
PreparedStatement
stmt=con.prepareStatement("insert into logintime values(?,?)");
stmt.setString(1,name);
stmt.setString(2, time);
stmt.executeUpdate();
HttpSession session
=request.getSession();
session.setAttribute("name", name);
RequestDispatcher
rd=request.getRequestDispatcher("ViewServlet");
rd.forward(request, response);
}else
{
out.println("<h4>Invalid UserName or
Password</h4>");
RequestDispatcher
rd=request.getRequestDispatcher("index.html");
rd.include(request, response);
}
}
catch(Exception
e){System.out.print(e);}
finally {
try {
out.close();
con.close();
} catch (SQLException ex) {
Logger.getLogger(LoginServlet.class.getName()).log(Level.SEVERE, null,
ex);
}
}
}
ViewServlet
package
nkpack;
import
java.io.IOException;
import
java.io.PrintWriter;
import
javax.servlet.ServletContext;
import
javax.servlet.ServletException;
import
javax.servlet.http.HttpServlet;
import
javax.servlet.http.HttpServletRequest;
import
javax.servlet.http.HttpServletResponse;
import
javax.servlet.http.HttpSession;
/**
*
* @author Navindra Jha
*/
public
class ViewServlet extends HttpServlet {
protected void
processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
HttpSession
session=request.getSession();
String
name=(String)session.getAttribute("name");
ServletContext ctx=getServletContext();
try {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet
ViewServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h2>Welcome
to you, "+name+"</h2>");
out.println("Total
Hits="+ctx.getAttribute("total"));
out.println("Current
User="+ctx.getAttribute("current"));
out.println("<a
href=LogoutServlet>Logout</a>");
out.println("<a
href=HitSpecifier>Details of Hit</a>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
MyListener
package
nkpack;
import
java.io.IOException;
import
javax.servlet.ServletContext;
import
javax.servlet.ServletContextEvent;
import
javax.servlet.ServletContextListener;
import
javax.servlet.ServletException;
import
javax.servlet.http.HttpSessionEvent;
import
javax.servlet.http.HttpSessionListener;
/**
*
* @author Navindra Jha
*/
public
class MyListener implements ServletContextListener,HttpSessionListener {
ServletContext ctx;
public void
contextInitialized(ServletContextEvent sce) {
ctx=sce.getServletContext();
ctx.setAttribute("current",new
Integer(0));
ctx.setAttribute("total",new
Integer(0));
}
public void
contextDestroyed(ServletContextEvent sce) {
throw new
UnsupportedOperationException("Not supported yet.");
}
public void sessionCreated(HttpSessionEvent
se) {
Integer
t=(Integer)ctx.getAttribute("total");
Integer
c=(Integer)ctx.getAttribute("current");
int tot=t.intValue();
int cur=c.intValue();
tot++;
cur++;
ctx.setAttribute("current",
cur);
ctx.setAttribute("total",
tot);
}
public void
sessionDestroyed(HttpSessionEvent se) {
Integer
c=(Integer)ctx.getAttribute("current");
int cur=c.intValue();
cur--;
ctx.setAttribute("current",
new Integer(cur));
}
}
HitSpecifier
package
nkpack;
import
java.io.IOException;
import
java.io.PrintWriter;
import
java.sql.Connection;
import
java.sql.DriverManager;
import
java.sql.ResultSet;
import
java.sql.SQLException;
import
java.sql.Statement;
import
java.util.logging.Level;
import
java.util.logging.Logger;
import
javax.servlet.ServletConfig;
import
javax.servlet.ServletException;
import
javax.servlet.http.HttpServlet;
import
javax.servlet.http.HttpServletRequest;
import
javax.servlet.http.HttpServletResponse;
/**
*
* @author Navindra Jha
*/
public
class HitSpecifier extends HttpServlet {
protected void
processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException,
IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("Hit
Details<br>");
Connection con=null;
try {
ServletConfig config =
getServletConfig();
String dclass =
config.getInitParameter("driverClass");
String cstr =
config.getInitParameter("conStr");
Class.forName(dclass);
con =
DriverManager.getConnection(cstr, "root", "");
System.out.println(con);
Statement pstmt =
con.createStatement();
ResultSet rset =
pstmt.executeQuery("SELECT * FROM logintime");
while (rset.next()) {
out.println(rset.getString(1)+" "+rset.getString(2));
out.println("<br>");
}
} catch (Exception e)
{System.out.println(e);
} finally {
try {
out.close();
con.close();
} catch (SQLException ex) {
Logger.getLogger(HitSpecifier.class.getName()).log(Level.SEVERE, null,
ex);
}
}
}
LogoutServlet
package
nkpack;
import
java.io.IOException;
import
java.io.PrintWriter;
import
javax.servlet.ServletException;
import
javax.servlet.http.HttpServlet;
import
javax.servlet.http.HttpServletRequest;
import
javax.servlet.http.HttpServletResponse;
import
javax.servlet.http.HttpSession;
/**
*
* @author Navindra Jha
*/
public
class LogoutServlet extends HttpServlet {
protected void
processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
HttpSession
session=request.getSession();
session.invalidate();
PrintWriter out = response.getWriter();
try {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet
LogoutServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>You are
Successfully logout</h1>");
out.print("<a
href=LoginServlet>Aganin Login</a>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
web.xml
<?xml
version="1.0" encoding="UTF-8"?>
<web-app
version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<listener>
<listener-class>nkpack.MyListener</listener-class>
</listener>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>nkpack.LoginServlet</servlet-class>
<init-param>
<param-name>driverClass</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
</init-param>
<init-param>
<param-name>conStr</param-name>
<param-value>jdbc:mysql://localhost:3306/stu</param-value>
</init-param>
</servlet>
<servlet>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>nkpack.LogoutServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>ViewServlet</servlet-name>
<servlet-class>nkpack.ViewServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>HitSpecifier</servlet-name>
<servlet-class>nkpack.HitSpecifier</servlet-class>
<init-param>
<param-name>driverClass</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
</init-param>
<init-param>
<param-name>conStr</param-name>
<param-value>jdbc:mysql://localhost:3306/stu</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/LogoutServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ViewServlet</servlet-name>
<url-pattern>/ViewServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>HitSpecifier</servlet-name>
<url-pattern>/HitSpecifier</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
Note: I have two table login and logintime
login
========
uname varchar
upass varchar
logintime
========
uname varchar
time time
Note: I have two table login and logintime
login
========
uname varchar
upass varchar
logintime
========
uname varchar
time time
No comments:
Post a Comment