The servlet implementation class must be sub type of Servlet Interface and should not be abstract.So the implementation class needs to implement all the methods declared in the Servlet interface even though it's not needed. To solve this problem the Servlet API provides a Adapter Class i.e., GenericServlet. This GenericServlet implemets the javax.Servlet.Servlet interface and provides the basic implementation for the methods except Service() method.
Showing posts with label Servlets. Show all posts
Showing posts with label Servlets. Show all posts
What Is Servlet and It's Advantages ?

Servlets are the components of Java that are used to create dynamic web applications. This can be run on any java enabled platform. Servlets are designed to process HTTP requests, such as GET and POST.
The Client and Server request processing using Servlet as below.
- A client sends a request to a servelt container, which acts as the web server.
- The web server searches the required servlet and initiates it.
- The servlet process the client request and sends the response back to the server, which is forwarded to the client.
Advantages of Servlet:
- Faster than CGI.
- Platform Independent. So this can be run on any java enabled platform.
- Used Standard vendor independent API supported by many web servers
- Servlets are server side component. So supports security provided by web server.
Auto Refresh in Servlets

The auto-refresh example below demonstrates how to create a save data using sessions after each refresh page. The example increments the counter of the number of times the servlets been accessed in every 5 seconds and displays it as output.
Example :
The method response.addHeader("Refresh", "5") refreshes the servlet after every 5 seconds till the servlet gets destroy.
Example :
import javax.servlet.*; import java.io.*; public class ClientAutoServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { HttpSession session = request.getSession(); Long times = (Long) session.getAttribute("times"); if (times == null) session.setAttribute("times", new Long(0)); long value = 1; if (times != null) value = (times.longValue()) + 1; response.addHeader("Refresh", "5"); response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); out.println("<html><head><title>Client Auto Refresh Example</title></head><body>"); out.println("The Counter below will automatically increase after 5 seconds<br/><br/>"); out.println("You've visited this page " + value + " times."); session.setAttribute("times", new Long(value)); out.println("</body></html>"); } }
The method response.addHeader("Refresh", "5") refreshes the servlet after every 5 seconds till the servlet gets destroy.
Structure of Web Applications

Web Applications use a standard directory structure defined in the Servlet specification. When developing web applications on J2EE platform, you must follow this structure so that application can be deployed in any J2EE compliant web server.
A web application has the directory structureas shown in below figure.
The root directory of the application is called the document root. Root directory is mapped to the context path. Root directory contains a directory named WEB-INF. Anything under the root directory excepting the WEB-INF directory is publically available, and can be accessed by URL from browser. WEB-INF directory is a private area of the web application, any files under WEB-INF directory cannot be accessed directly from browser by specifying the URL like http://somesite/WEB-INF/someresource.html. Web container will not serve the content of this directory. However the content of the WEB-INF directory is accessible by the classes within the application. So if there are any resources like JSPs or HTML document that you don’t wish to be accessible directly from web browser, you should place it under WEB-INF directory.
WEB-INF directory structure
WEB-INF directory contains- WEB-INF/web.xml deployment descriptor
- WEB-INF/classes directory
- WEB-INF/lib directory
/WEB-INF/web.xml
web.xml is called the web application deployment descriptor. This is a XML file that defines servlets, servlet mappings, listeners, filters, welcome files etc. Deployment descriptor is a heart of any J2EE web application, so every web application must have a web.xml deployment descriptor directly under WEB-INF folder.
/WEB-INF/classes
The classes directory is used to store compiled servlet and other classes of the application. If your classes are organized into packages, the directory structure must be reflected directly under WEB-INF/classes directory. The classes directory is automatically included in CLASSPATH.
/WEB-INF/lib
Lib directory is used to store the jar files. If application has any bundled jar files, or if application uses any third party libraries such as log4j, JDBC drivers which is packaged in jar file, than these jar files should be placed in lib directory.
All unpacked classes and resources in the /WEB-INF/classes directory, plus classes and resources in JAR files under the /WEB-INF/lib directory are included in classpath and made visible to the containing web application.
Servlet Container

A servlet container is nothing but a compiled, executable program. The main function of the container is to load, initialize and execute servlets. The servlet container is the official Reference Implementation for the Java Servlet and JavaServer Pages technologies. The Java Servlet and JavaServer Pages specifications are developed by Sun under the Java Community Process.
The servlet container together with the web server (or application server) provides the HTTP interface to the world. It is also possible for a servlet container to run stand alone (without web server) or to even run on another host than the web server. When a request is received by the servlet container, it decides what servlet to call in accordance with a configuration file. The servlet Container calls the servlet's service() method and passes an instance of ServletRequest and ServletResponse. Depending on the request's method (mostly GET and POST), service calls doGet() or doPost().
These passed instances can be used by the servlet to find out who the remote user is, if and what HTTP POST parameters have been set and other characteristics. The servlet container is responsible for loading and instantiating the servlets and then calling init().
The container is designed to perform well while serving large numbers of requests. A container can hold any number of active servlets, filters, and listeners. Both the container and the objects in the container are multithreaded. The container creates and manages threads as necessary to handle incoming requests. The container handles multiple requests concurrently, and more than one thread may enter an object at a time. Therefore, each object within a container must be threadsafe.
The servlet container together with the web server (or application server) provides the HTTP interface to the world. It is also possible for a servlet container to run stand alone (without web server) or to even run on another host than the web server. When a request is received by the servlet container, it decides what servlet to call in accordance with a configuration file. The servlet Container calls the servlet's service() method and passes an instance of ServletRequest and ServletResponse. Depending on the request's method (mostly GET and POST), service calls doGet() or doPost().
These passed instances can be used by the servlet to find out who the remote user is, if and what HTTP POST parameters have been set and other characteristics. The servlet container is responsible for loading and instantiating the servlets and then calling init().
The container is designed to perform well while serving large numbers of requests. A container can hold any number of active servlets, filters, and listeners. Both the container and the objects in the container are multithreaded. The container creates and manages threads as necessary to handle incoming requests. The container handles multiple requests concurrently, and more than one thread may enter an object at a time. Therefore, each object within a container must be threadsafe.
Advantages of JSP over Servlet.

- Efficient: With traditional CGI, a new process is started for each HTTP request. If the CGI program does a relatively fast operation, the overhead of starting the process can dominate the execution time. With servlets, the Java Virtual Machine stays up, and each request is handled by a lightweight Java thread, not a heavyweight operating system process. Similarly, in traditional CGI, if there are N simultaneous request to the same CGI program, then the code for the CGI program is loaded into memory N times. With servlets, however, there are N threads but only a single copy of the servlet class. Servlets also have more alternatives than do regular CGI programs for optimizations such as caching previous computations, keeping database connections open, and the like.
- Convenient: Hey, you already know Java. Why learn Perl too? Besides the convenience of being able to use a familiar language, servlets have an extensive infrastructure for automatically parsing and decoding HTML form data, reading and setting HTTP headers, handling cookies, tracking sessions, and many other such utilities.
- Powerful: Java servlets let you easily do several things that are difficult or impossible with regular CGI. For one thing, servlets can talk directly to the Web server (regular CGI programs can't). This simplifies operations that need to look up images and other data stored in standard places. Servlets can also share data among each other, making useful things like database connection pools easy to implement. They can also maintain information from request to request, simplifying things like session tracking and caching of previous computations.
- Portable: Servlets are written in Java and follow a well-standardized API. Consequently, servlets written for, say I-Planet Enterprise Server can run virtually unchanged on Apache, Microsoft IIS, or WebStar. Servlets are supported directly or via a plugin on almost every major Web server.
- Inexpensive: There are a number of free or very inexpensive Web servers available that are good for "personal" use or low-volume Web sites. However, with the major exception of Apache, which is free, most commercial-quality Web servers are relatively expensive. Nevertheless, once you have a Web server, no matter the cost of that server, adding servlet support to it (if it doesn't come preconfigured to support servlets) is generally free or cheap.
Why Can't Use constructor instead of init method to initialize servlet

Can we use the constructor, instead of init(), to initialize servlet?
Yes. But you will not get the servlet specific things from constructor. The
original reason for init() was that ancient versions of Java couldn t dynamically
invoke constructors with arguments, so there was no way to give the
constructor aServletConfig. That no longer applies, but servlet containers still
will only callyour no-arg constructor. So you won t have access to a
ServletConfig or ServletContext.
Difference Between Servlets And Jsp

Servlets and Java Server Pages are complementary APIs, both providing a means for generating dynamic Web content. A servlet is a Java class implementing the javax.servlet.Servlet interface that runs within a Web or application server's servlet engine, servicing client requests forwarded to it through the server. A Java Server Page is a slightly more complicated beast. JSP pages contain a mixture of HTML, Java scripts (not to be confused with JavaScript), JSP elements, and JSP directives. The elements in a Java Server Page will generally be compiled by the JSP engine into a servlet, but the JSP specification only requires that the JSP page execution entity follow the Servlet Protocol.
The advantage of Java Server Pages is that they are document-centric. Servlets, on the other hand, look and act like programs. A Java Server Page can contain Java program fragments that instantiate and execute Java classes, but these occur inside an HTML template file and are primarily used to generate dynamic content. Some of the JSP functionality can be achieved on the client, using JavaScript. The power of JSP is that it is server-based and provides a framework for Web application development. Rather than choosing between servlets and Java Server Pages, you will find that most non-trivial applications will want to use a combination of JSP and servlets. In fact, the JSP 1.1 and Servlet 2.2 specifications are based around the concept of the Web application, combining the two APIs into a unified framework.
Storing and Retrieving Session Objects using Servlets

• Retrieve a session object across multiple requests to the same or different servlets within the same WebApp.
• Store objects into a session object.
• Retrieve objects from a session object.
So, without any further delays, lets get started!!!
Storing & Retrieving Session Objects:
Using the session is easier said that done. Explaining it as paragraphs would be an arduous and not to mention a boring task. So lets take a look at some sample code that will tell us how to achieve session persistence in our code.
Let me remind you that, please pay attention to the code. You can easily overlook/miss many of the nuances of the session usage and that could cost you dearly in the exam.
Example Code 1:
In this below example, we are going to see how to obtain or rather create a new session and use it.
/**
* Return the session associated with this Request
* If it doesn't, then creating one if necessary
*/
public HttpSession getSession(boolean create)
{
if( System.getSecurityManager() != null )
{
PrivilegedGetSession dp = new PrivilegedGetSession(create);
return (HttpSession)AccessController.doPrivileged(dp);
}
return doGetSession(create);
}
private HttpSession doGetSession(boolean create)
{
// Check if Context exists if not, a session cannot exist
if (context == null)
return (null);
// Return the current session if it exists and is valid
if ((session != null) && !session.isValid())
session = null;
if (session != null)
return (session.getSession());
// Return the requested session if it exists and is valid
Manager manager = null;
if (context != null)
manager = context.getManager();
if (manager == null)
return (null);
if (requestedSessionId != null)
{
try
{
session = manager.findSession(requestedSessionId);
} catch (IOException e) {
session = null;
}
if ((session != null) && !session.isValid())
session = null;
if (session != null) {
return (session.getSession());
}
}
// Create a new session if requested & response is not committed
if (!create)
return (null);
if ((context != null) && (response != null) && context.getCookies() &&
response.getResponse().isCommitted())
{
throw new IllegalStateException(sm.getString("httpRequestBase.createCommitted"));
}
session = manager.createSession();
if (session != null)
return (session.getSession());
else
return (null);
}
/**
* Return true if the session identifier
* included in this request came from a cookie.
*/
public boolean isRequestedSessionIdFromCookie()
{
if (requestedSessionId != null)
return (requestedSessionCookie);
else
return (false);
}
/**
* Return true if the session identifier
* included in this request came from the request URI.
*/
public boolean isRequestedSessionIdFromURL()
{
if (requestedSessionId != null)
return (requestedSessionURL);
else
return (false);
}
Actually, above is how your Tomcat server handles your request to create a session object. Now that we know this let us take a look at another example that is going to actually use this session to do something worthwhile.
Example Code 2:
This is quite a long piece of code. In this example, we will be accessing the session, setting some attributes in it as well as getting some. Also, we are accessing the cookies in the request and using them all to print out some stuff in the web browser.
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import javax.servlet.*;
import javax.servlet.http.*;
public class TestSessionsServlet extends HttpServlet
{
// The regular doPost method
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doGet(request,response);
}
// The regular doGet method
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
// Get the session associated with this request
// A new session would get created if it doesn't exist
HttpSession session = request.getSession(true);
// Set some value into the session as attribute
session.setAttribute("sessionId", new Integer(22));
// Try to read some data from the Session
String cookieName = request.getParameter("cookiename");
String cookieValue = request.getParameter("cookievalue");
// It is always a good idea to check for null if a value is
// picked up from the session. If the value you are looking
// for doesn't exist, you will end up with
// a NullPointerException
if (cookieName != null && cookieValue != null)
{
Cookie cookie = new Cookie(cookieName, cookieValue);
response.addCookie(cookie);
}
// Write some stuff on the browser
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.println("< html >");
out.println(" < head >");
out.println(" < title >Session Detail Report< / title >");
out.println(" < / head >");
out.println(" < body >");
out.println(" < center >");
out.println(" < h2 >Session Detail Report< / h2 >");
String url=request.getScheme()+ "://"+request.getServerName()+
":"+request.getServerPort()+ request.getRequestURI();
out.println(" < table width=\"100%\" border=\"1\" + " cellspacing=\"0\" cellpadding=\"1\" >");
out.println(" < tr >");
out.println(" < td colspan=2 >"+url+"< / td >");
out.println(" < / tr >");
printVoid(out);
out.println(" < tr >");
out.println(" < td colspan=2 >");
out.print("< form action=\""); out.println(url + "\" method=POST >");
out.println("Attribute Name:< input type=text "+"length=20 name=cookiename > < br >");
out.println("Attribute Value:< input type=text"+"length=20 name=cookievalue > < br >");
out.println("< input type=submit >< / form >");
out.println(" < / td >");
out.println(" < / tr >");
printHeader(out,"Cookies in this request:");
// Get all cookies from the Request
Cookie[] cookies = request.getCookies();
if (cookies!=null)
for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; printValue(out,cookie.getName(), cookie.getValue()); } printVoid(out); printHeader(out,"Session Details:"); SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss.SSS z"); printValue(out,"Requested Session Id:", request.getRequestedSessionId()); printValue(out,"Current Session Id:", session.getId()); printValue(out,"Session Created Time:", format.format(new Date(session.getCreationTime()))); printValue(out,"Session Last Accessed Time:", format.format(new Date(session.getLastAccessedTime()))); printValue(out,"Session Max Inactive " + "Interval Seconds:", Integer.toString(session.getMaxInactiveInterval())); printVoid(out); printHeader(out,"Session values:"); Enumeration enum = session.getAttributeNames(); while (enum.hasMoreElements()) { String key = (String) enum.nextElement(); Object val = session.getAttribute(key); printValue(out,key,val.toString()); } printVoid(out); out.println(" < / td >");
out.println(" < / tr >");
out.println(" < / table >");
out.println(" < / body >");
out.println("< / html >");
out.flush();
}
// Utility methods
public void printHeader(PrintWriter out, String header)
{
out.println(" < tr >");
out.println(" < td bgcolor=\"#999999\" "); out.println(" "colspan=\"2\" >");
out.println(" < b >"+header+"< / b >");
out.println(" < / td >");
out.println(" < / tr >");
}
public void printValue(PrintWriter out, String key, String val)
{
if (val!=null) {
if (val.length()>255)
val=val.substring(0,128)+" (... more)";
}
out.println(" < tr >");
out.println(" < td bgcolor=\"#cccccc\" >"+ key + "< / td >");
out.println(" < td bgcolor=\"#ffffff\" >"+ val + "< / td >");
out.println(" < / tr >");
}
public void printVoid(PrintWriter out)
{
out.println("< tr > < td bgcolor=\"#ffffff\" "+"colspan=\"2\" > < / td >< / tr >");
}
}
You can do a lot more with the details above but to keep it simple, we aren’t attempting anything complicated since this is one of our first examples of using Sessions.
The output of the above servlet would vary based on time and the list of attributes that are already existent in the Session.
• Store objects into a session object.
• Retrieve objects from a session object.
So, without any further delays, lets get started!!!
Storing & Retrieving Session Objects:
Using the session is easier said that done. Explaining it as paragraphs would be an arduous and not to mention a boring task. So lets take a look at some sample code that will tell us how to achieve session persistence in our code.
Let me remind you that, please pay attention to the code. You can easily overlook/miss many of the nuances of the session usage and that could cost you dearly in the exam.
Example Code 1:
In this below example, we are going to see how to obtain or rather create a new session and use it.
/**
* Return the session associated with this Request
* If it doesn't, then creating one if necessary
*/
public HttpSession getSession(boolean create)
{
if( System.getSecurityManager() != null )
{
PrivilegedGetSession dp = new PrivilegedGetSession(create);
return (HttpSession)AccessController.doPrivileged(dp);
}
return doGetSession(create);
}
private HttpSession doGetSession(boolean create)
{
// Check if Context exists if not, a session cannot exist
if (context == null)
return (null);
// Return the current session if it exists and is valid
if ((session != null) && !session.isValid())
session = null;
if (session != null)
return (session.getSession());
// Return the requested session if it exists and is valid
Manager manager = null;
if (context != null)
manager = context.getManager();
if (manager == null)
return (null);
if (requestedSessionId != null)
{
try
{
session = manager.findSession(requestedSessionId);
} catch (IOException e) {
session = null;
}
if ((session != null) && !session.isValid())
session = null;
if (session != null) {
return (session.getSession());
}
}
// Create a new session if requested & response is not committed
if (!create)
return (null);
if ((context != null) && (response != null) && context.getCookies() &&
response.getResponse().isCommitted())
{
throw new IllegalStateException(sm.getString("httpRequestBase.createCommitted"));
}
session = manager.createSession();
if (session != null)
return (session.getSession());
else
return (null);
}
/**
* Return true if the session identifier
* included in this request came from a cookie.
*/
public boolean isRequestedSessionIdFromCookie()
{
if (requestedSessionId != null)
return (requestedSessionCookie);
else
return (false);
}
/**
* Return true if the session identifier
* included in this request came from the request URI.
*/
public boolean isRequestedSessionIdFromURL()
{
if (requestedSessionId != null)
return (requestedSessionURL);
else
return (false);
}
Actually, above is how your Tomcat server handles your request to create a session object. Now that we know this let us take a look at another example that is going to actually use this session to do something worthwhile.
Example Code 2:
This is quite a long piece of code. In this example, we will be accessing the session, setting some attributes in it as well as getting some. Also, we are accessing the cookies in the request and using them all to print out some stuff in the web browser.
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import javax.servlet.*;
import javax.servlet.http.*;
public class TestSessionsServlet extends HttpServlet
{
// The regular doPost method
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doGet(request,response);
}
// The regular doGet method
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
// Get the session associated with this request
// A new session would get created if it doesn't exist
HttpSession session = request.getSession(true);
// Set some value into the session as attribute
session.setAttribute("sessionId", new Integer(22));
// Try to read some data from the Session
String cookieName = request.getParameter("cookiename");
String cookieValue = request.getParameter("cookievalue");
// It is always a good idea to check for null if a value is
// picked up from the session. If the value you are looking
// for doesn't exist, you will end up with
// a NullPointerException
if (cookieName != null && cookieValue != null)
{
Cookie cookie = new Cookie(cookieName, cookieValue);
response.addCookie(cookie);
}
// Write some stuff on the browser
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.println("< html >");
out.println(" < head >");
out.println(" < title >Session Detail Report< / title >");
out.println(" < / head >");
out.println(" < body >");
out.println(" < center >");
out.println(" < h2 >Session Detail Report< / h2 >");
String url=request.getScheme()+ "://"+request.getServerName()+
":"+request.getServerPort()+ request.getRequestURI();
out.println(" < table width=\"100%\" border=\"1\" + " cellspacing=\"0\" cellpadding=\"1\" >");
out.println(" < tr >");
out.println(" < td colspan=2 >"+url+"< / td >");
out.println(" < / tr >");
printVoid(out);
out.println(" < tr >");
out.println(" < td colspan=2 >");
out.print("< form action=\""); out.println(url + "\" method=POST >");
out.println("Attribute Name:< input type=text "+"length=20 name=cookiename > < br >");
out.println("Attribute Value:< input type=text"+"length=20 name=cookievalue > < br >");
out.println("< input type=submit >< / form >");
out.println(" < / td >");
out.println(" < / tr >");
printHeader(out,"Cookies in this request:");
// Get all cookies from the Request
Cookie[] cookies = request.getCookies();
if (cookies!=null)
for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; printValue(out,cookie.getName(), cookie.getValue()); } printVoid(out); printHeader(out,"Session Details:"); SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss.SSS z"); printValue(out,"Requested Session Id:", request.getRequestedSessionId()); printValue(out,"Current Session Id:", session.getId()); printValue(out,"Session Created Time:", format.format(new Date(session.getCreationTime()))); printValue(out,"Session Last Accessed Time:", format.format(new Date(session.getLastAccessedTime()))); printValue(out,"Session Max Inactive " + "Interval Seconds:", Integer.toString(session.getMaxInactiveInterval())); printVoid(out); printHeader(out,"Session values:"); Enumeration enum = session.getAttributeNames(); while (enum.hasMoreElements()) { String key = (String) enum.nextElement(); Object val = session.getAttribute(key); printValue(out,key,val.toString()); } printVoid(out); out.println(" < / td >");
out.println(" < / tr >");
out.println(" < / table >");
out.println(" < / body >");
out.println("< / html >");
out.flush();
}
// Utility methods
public void printHeader(PrintWriter out, String header)
{
out.println(" < tr >");
out.println(" < td bgcolor=\"#999999\" "); out.println(" "colspan=\"2\" >");
out.println(" < b >"+header+"< / b >");
out.println(" < / td >");
out.println(" < / tr >");
}
public void printValue(PrintWriter out, String key, String val)
{
if (val!=null) {
if (val.length()>255)
val=val.substring(0,128)+" (... more)";
}
out.println(" < tr >");
out.println(" < td bgcolor=\"#cccccc\" >"+ key + "< / td >");
out.println(" < td bgcolor=\"#ffffff\" >"+ val + "< / td >");
out.println(" < / tr >");
}
public void printVoid(PrintWriter out)
{
out.println("< tr > < td bgcolor=\"#ffffff\" "+"colspan=\"2\" > < / td >< / tr >");
}
}
You can do a lot more with the details above but to keep it simple, we aren’t attempting anything complicated since this is one of our first examples of using Sessions.
The output of the above servlet would vary based on time and the list of attributes that are already existent in the Session.
Servlets - Auto Page Refresh

Consider a webpage which is displaying live game score or stock market status or currency exchange ration. For all such type of pages, you would need to refresh your web page regularly using refresh or reload button with your browser.
Java Servlet makes this job easy by providing you a mechanism where you can make a webpage in such a way that it would refresh automatically after a given interval.
The simplest way of refreshing a web page is using method setIntHeader() of response object. Following is the signature of this method:
public void setIntHeader(String header, int headerValue) |
This method sends back header "Refresh" to the browser along with an integer value which indicates time interval in seconds.
Auto Page Refresh Example:
This example shows how a servlet performs auto page refresh using setIntHeader() method to set Refresh header.
// Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; // Extend HttpServlet class public class Refresh extends HttpServlet { // Method to handle GET method request. public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set refresh, autoload time as 5 seconds response.setIntHeader("Refresh", 5); // Set response content type response.setContentType("text/html"); // Get current time Calendar calendar = new GregorianCalendar(); String am_pm; int hour = calendar.get(Calendar.HOUR); int minute = calendar.get(Calendar.MINUTE); int second = calendar.get(Calendar.SECOND); if(calendar.get(Calendar.AM_PM) == 0) am_pm = "AM"; else am_pm = "PM"; String CT = hour+":"+ minute +":"+ second +" "+ am_pm; PrintWriter out = response.getWriter(); String title = "Auto Page Refresh using Servlet"; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n"+ "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<p>Current Time is: " + CT + "</p>\n"); } // Method to handle POST method request. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } |
Now let us compile above servlet and create following entries in web.xml
.... <servlet> <servlet-name>Refresh</servlet-name> <servlet-class>Refresh</servlet-class> </servlet> <servlet-mapping> <servlet-name>Refresh</servlet-name> <url-pattern>/Refresh</url-pattern> </servlet-mapping> .... |
Now call this servlet using URL http://localhost:8080/Refresh which would display current system time after every 5 seconds as follows. Just run the servlet and wait to see the result:
Auto Page Refresh using Servlet
Current Time is: 9:44:50 PM
|
Servlets - Session Tracking

HTTP is a "stateless" protocol which means each time a client retrieves a Web page, the client opens a separate connection to the Web server and the server automatically does not keep any record of previous client request.
Still there are following three ways to maintain session between web client and web server:
(1) Cookies:
A webserver can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the recieved cookie.
This may not be an effective way because many time browser does nots upport a cookie, so I would not recommend to use this procedure to maintain the sessions.
(2) Hidden Form Fields:
A web server can send a hidden HTML form field along with a unique session ID as follows:
<input type="hidden" name="sessionid" value="12345">
|
This entry means that, when the form is submitted, the specified name and value are automatically included in the GET or POST data. Each time when web browser sends request back, then session_id value can be used to keep the track of different web browsers.
This could be an effective way of keeping track of the session but clicking on a regular (<A HREF...>) hypertext link does not result in a form submission, so hidden form fields also cannot support general session tracking.
(3) URL Rewriting:
You can append some extra data on the end of each URL that identifies the session, and the server can associate that session identifier with data it has stored about that session.
For example, with http://tutorialspoint.com/file.htm;sessionid=12345, the session identifier is attached as sessionid=12345 which can be accessed at the web server to identify the client.
URL rewriting is a better way to maintain sessions and works for the browsers when they don't support cookies but here drawback is that you would have generate every URL dynamically to assign a session ID though page is simple static HTML page.
The HttpSession Object:
Apart from the above mentioned three ways, servlet provides HttpSession Interface which provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user.
The servlet container uses this interface to create a session between an HTTP client and an HTTP server. The session persists for a specified time period, across more than one connection or page request from the user.
You would get HttpSession object by calling the public method getSession() of HttpServletRequest, as below:
HttpSession session = request.getSession();
|
You need to call request.getSession() before you send any document content to the client. Here is a summary of the important methods available through HttpSession object:
S.N. | Method & Description |
---|---|
1 | public Object getAttribute(String name) This method returns the object bound with the specified name in this session, or null if no object is bound under the name. |
2 | public Enumeration getAttributeNames() This method returns an Enumeration of String objects containing the names of all the objects bound to this session. |
3 | public long getCreationTime() This method returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT. |
4 | public String getId() This method returns a string containing the unique identifier assigned to this session. |
5 | public long getLastAccessedTime() This method returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT. |
6 | public int getMaxInactiveInterval() This method returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses. |
7 | public void invalidate() This method invalidates this session and unbinds any objects bound to it. |
8 | public boolean isNew( This method returns true if the client does not yet know about the session or if the client chooses not to join the session. |
9 | public void removeAttribute(String name) This method removes the object bound with the specified name from this session. |
10 | public void setAttribute(String name, Object value) This method binds an object to this session, using the name specified. |
11 | public void setMaxInactiveInterval(int interval) This method specifies the time, in seconds, between client requests before the servlet container will invalidate this session. |
Session Tracking Example:
This example describes how to use the HttpSession object to find out the creation time and the last-accessed time for a session. We would associate a new session with the request if one does not already exist.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
// Extend HttpServlet class
public class SessionTrack extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Create a session object if it is already not created.
HttpSession session = request.getSession(true);
// Get session creation time.
Date createTime = new Date(session.getCreationTime());
// Get last access time of this web page.
Date lastAccessTime =
new Date(session.getLastAccessedTime());
String title = "Welcome Back to my website";
Integer visitCount = new Integer(0);
String visitCountKey = new String("visitCount");
String userIDKey = new String("userID");
String userID = new String("ABCD");
// Check if this is new comer on your web page.
if (session.isNew()){
title = "Welcome to my website";
session.setAttribute(userIDKey, userID);
} else {
visitCount = (Integer)session.getAttribute(visitCountKey);
visitCount = visitCount + 1;
userID = (String)session.getAttribute(userIDKey);
}
session.setAttribute(visitCountKey, visitCount);
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<h2 align=\"center\">Session Infomation</h2>\n" +
"<table border=\"1\" align=\"center\">\n" +
"<tr bgcolor=\"#949494\">\n" +
" <th>Session info</th><th>value</th></tr>\n" +
"<tr>\n" +
" <td>id</td>\n" +
" <td>" + session.getId() + "</td></tr>\n" +
"<tr>\n" +
" <td>Creation Time</td>\n" +
" <td>" + createTime +
" </td></tr>\n" +
"<tr>\n" +
" <td>Time of Last Access</td>\n" +
" <td>" + lastAccessTime +
" </td></tr>\n" +
"<tr>\n" +
" <td>User ID</td>\n" +
" <td>" + userID +
" </td></tr>\n" +
"<tr>\n" +
" <td>Number of visits</td>\n" +
" <td>" + visitCount + "</td></tr>\n" +
"</table>\n" +
"</body></html>");
}
}
|
Compile above servlet SessionTrack and create appropriate entry in web.xml file. Now runninghttp://localhost:8080/SessionTrack would display the following result when you would run for the first time:
Welcome to my website
Session Infomation
Session info | value |
---|---|
id | 0AE3EC93FF44E3C525B4351B77ABB2D5 |
Creation Time | Tue Jun 08 17:26:40 GMT+04:00 2010 |
Time of Last Access | Tue Jun 08 17:26:40 GMT+04:00 2010 |
User ID | ABCD |
Number of visits | 0 |
Now try to run the same servlet for second time, it would display following result.
Welcome Back to my website
Session Infomation
info type | value |
---|---|
id | 0AE3EC93FF44E3C525B4351B77ABB2D5 |
Creation Time | Tue Jun 08 17:26:40 GMT+04:00 2010 |
Time of Last Access | Tue Jun 08 17:26:40 GMT+04:00 2010 |
User ID | ABCD |
Number of visits | 1 |
Deleting Session Data:
When you are done with a user's session data, you have several options:
- Remove a particular attribute: You can call public void removeAttribute(String name)method to delete the value associated with a particular key.
- Delete the whole session: You can call public void invalidate() method to discard an entire session.
- Setting Session timeout: You can call public void setMaxInactiveInterval(int interval)method to set the timeout for a session individually.
- Log the user out: The servers that support servlets 2.4, you can call logout to log the client out of the Web server and invalidate all sessions belonging to all the users.
- web.xml Configuration: If you are using Tomcat, apart from the above mentioned methods, you can configure session time out in web.xml file as follows.
<session-config>
<session-timeout>15</session-timeout>
</session-config>
|
The timeout is expressed as minutes, and overrides the default timeout which is 30 minutes in Tomcat.
The getMaxInactiveInterval( ) method in a servlet returns the timeout period for that session in seconds. So if your session is configured in web.xml for 15 minutes, getMaxInactiveInterval( ) returns 900.