Counter Class
Copy and paste the following code into a new .java file and save it as 'Counter.java'
in the CATALINA_HOME/webapps/star/WEB-INF/classes/com/stardeveloper/example/ directory.
Note that CATALINA_HOME is the directory where you have installed Tomcat 4.0 server. I
am assuming that you have Tomcat 4.0 server on your system, since this example uses
Servlet 2.2 API you can use any Servlet 2.2 API capable Servlet Container of your choice.
You can then change the path above with the one provided by your Servlet Container.
package com.stardeveloper.example;
import java.io.Serializable;
public class Counter implements Serializable {
private int count = 0;
public int getCount() {
return this.count;
}
public void increment() {
this.count++;
}
}
Explanation
Above is a simple Java class which contains a private int variable named
'count'. Then there are two methods, one getter and the second one
( increment() ) increments the internal variable 'count' by 1. getCount()
will return the value of 'count' variable that is the number of pages user has viewed.
Now compile 'Counter.java' file and make sure that it is in the right folder ( see
above ).
We are done with 'Counter' class so lets move forward to build our Servlet
which will bind this class to the user session and keep track of the number of times page
has been viewed and will also display some other useful information about the session to
the user.
TestSessionServlet
We will name our Servlet 'TestSessionServlet'. Create a new .java file, copy and paste
the following code in it. Save it as 'TestSessionServlet.java' in the
CATALINA_HOME/webapps/star/WEB-INF/classes/com/stardeveloper/servlets/ folder and compile
it.
package com.stardeveloper.servlets;
import java.io.*;
import java.util.Date;
import com.stardeveloper.example.Counter;
import javax.servlet.*;
import javax.servlet.http.*;
public class TestSessionServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
res.setContentType("text/html");
// got hold of the user session
PrintWriter out = res.getWriter();
HttpSession session = req.getSession(true);
// declare out Counter object
Counter counter;
if(session.isNew()) {
counter = new Counter();
session.setAttribute("counter", counter);
}
// incrementing page view count in our Counter object
counter = ((Counter)session.getAttribute("counter"));
counter.increment();
// retrieving session info
long currentTime = System.currentTimeMillis();
long creationTime = session.getCreationTime();
long lastAccessed = session.getLastAccessedTime();
long maxInterval = session.getMaxInactiveInterval();
String sessionId = session.getId();
String mode = req.getParameter("mode");
// print content
out.print("<html><head>");
out.print("<style>body, p { font-family:tahoma;");
out.print("font-size:12pt; } a { text-decoration:none;");
out.print("color:blue; }</style></head>");
out.print("<body>");
if(session.isNew()) {
out.print("<p>New Session created.</p>");
} else {
out.print("<p>Old Session. ");
out.print("Age : ");
out.print( (currentTime - creationTime) / 60000 );
out.print(" minutes.</p>");
}
out.print("<p>You have visited this page : ");
out.print( counter.getCount() );
out.print(" times.<br>");
out.print("Created at : ");
out.print( new Date(creationTime) );
out.print("<br>");
out.print("Last accessed : ");
out.print( new Date(lastAccessed) );
out.print("<br>");
out.print("SessionID : ");
out.print( sessionId );
out.print("</p><p>");
out.print("Note! Session will be inactivated after ");
out.print("a period of inactivity of <b>");
out.print( (maxInterval / 60) );
out.print("</b> minutes.");
out.print("</p><p>");
if( mode != null && mode.equals("invalidate")) {
session.invalidate();
out.print("<a href=\"/servlet/com.stardeveloper.");
out.print("servlets.TestSessionServlet\">");
out.print("Start New Session.</a>");
} else {
out.print("<a href=\"/servlet/");
out.print("com.stardeveloper.servlets.");
out.print("TestSessionServlet?mode=invalidate\">");
out.print("Invalidate this Session.</a>");
}
out.print("<p align=\"center\">");
out.print("<a href=\"http://www.stardeveloper.com\" ");
out.print("style=\"font-size:8pt;color:silver;\">");
out.print("© Stardeveloper.com</a></p>");
out.print("</p></body></html>");
out.close();
}
}
Explanation
Above code is extremely simple. Our TestSessionServlet class extends
HttpServlet class and overrides just one method, doGet(). In
this method we first get a reference to PrintWriter object to write
content back to the client. Next we get reference to the user session using HttpServletRequest
interface's getSession() method.
Then we declare our Counter object and if the session is new then
create a new Counter object and bind it to the user using setAttribute()
method we learned earlier.
Then we get reference to our Counter object from the user session using
getAttribute() method and increment the page view count by 1.
Next we declare different variables to receive different values from the user session.
Then we output plain HTML to the user along with session info we obtained. simple!
Once finished we close the PrintWriter object.