Signup · Login
Stardeveloper.com  
Home · Tutorials · Forums · ASP.NET Newsletter Application · Web Hosting Plans · Faisal Khan's Blog · Contact
Search Stardeveloper.com
Newsletter
Enter your email address to receive full length articles at Stardeveloper:


Article Categories
.NET  .NET
  ASP (16)
  ASP.NET (41)
  ADO (16)
  ADO.NET (11)
  COM (6)
  Web Services (4)
  C# (1)
  VB.NET (3)
  IIS (2)

J2EE  J2EE
  JSP (15)
  Servlets (9)
  Web Services (1)
  EJB (4)
  JDBC (4)
  E-Commerce (1)
  J2ME (1)
  Products (1)
  Applets (1)
  Patterns (1)

Main Category  Other
  Website Maintenance (3)
Log In
UserName Or Email:

Password:

Auto-Login:

Hosted by Securewebs.com
 
Home : J2EE : Servlets : Managing Sessions with Java Servlets
 
Read full length articles at Stardeveloper using Twitter Follow on Twitter Facebook Facebook fan page Email Get Articles via Email RSS Get Articles via RSS Feed

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.


Previous ( 1 Gone )( 1 Remaining ) Next

Comments/Questions ( Threads: 4, Comments: 4 )
    Contains 1 or more replies by the Author of this Article.
    Contains 1 or more replies by Faisal Khan.

  1. outstreams redirected in java
  2. Sessions
  3. Session in JSP for Login & Logout

Post Comments/Questions

In order to post questions/comments, you must be logged-in. If you are not a member yet, then signup, otherwise login. Once you login then come back to this page and you'll see a form right here which will allow you to post comments/questions.

Please note, one of the benefits of signing up is to be notified immediately by email everytime you receive a reply to the thread you have subscribed.

 
© 1999 - 2010 Stardeveloper.com, All Rights Reserved.