Beruflich Dokumente
Kultur Dokumente
Using Servlets, you can collect input from users through web page forms, present records from a
database or another source, and create web pages dynamically.
Java Servlets often serve the same purpose as programs implemented using the Common Gateway
Interface (CGI). But Servlets offer several advantages in comparison with the CGI.
Servlets Architecture
The following diagram shows the position of Servlets in a Web Application.
Page 1 of 36
Servlet Notes Advanced Java Programming
Servlets Tasks
Servlets perform the following major tasks −
• Read the explicit data sent by the clients (browsers). This includes an HTML form on a
Web page or it could also come from an applet or a custom HTTP client program.
• Read the implicit HTTP request data sent by the clients (browsers). This includes cookies,
media types and compression schemes the browser understands, and so forth.
• Process the data and generate the results. This process may require talking to a database,
executing an RMI or CORBA call, invoking a Web service, or computing the response
directly.
• Send the explicit data (i.e., the document) to the clients (browsers). This document can be
sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel,
etc.
• Send the implicit HTTP response to the clients (browsers). This includes telling the
browsers or other clients what type of document is being returned (e.g., HTML), setting
cookies and caching parameters, and other such tasks.
Servlets Packages
Java Servlets are Java classes run by a web server that has an interpreter that supports the Java
Servlet specification.
Servlets can be created using the javax.servlet and javax.servlet.http packages, which are a
standard part of the Java's enterprise edition, an expanded version of the Java class library that
supports large-scale development projects.
Java servlets have been created and compiled just like any other Java class. After you install the
servlet packages and add them to your computer's Classpath, you can compile servlets with the
JDK's Java compiler or any other current compiler.
Page 2 of 36
Servlet Notes Advanced Java Programming
When a user invokes a servlet, a single instance of each servlet gets created, with each user request
resulting in a new thread that is handed off to doGet or doPost as appropriate. The init() method
simply creates or loads some data that will be used throughout the life of the servlet.
Each time the server receives a request for a servlet, the server spawns a new thread and calls
service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.)
and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
Page 3 of 36
Servlet Notes Advanced Java Programming
The service () method is called by the container and service method invokes doGet, doPost, doPut,
doDelete, etc. methods as appropriate. So you have nothing to do with service() method but you
override either doGet() or doPost() depending on what type of request you receive from the client.
The doGet() and doPost() are most frequently used methods with in each service request. Here is
the signature of these two methods.
After the destroy() method is called, the servlet object is marked for garbage collection. The
destroy method definition looks like this −
Page 4 of 36
Servlet Notes Advanced Java Programming
Architecture Diagram
The following figure depicts a typical servlet life-cycle scenario.
• First the HTTP requests coming to the server are delegated to the servlet container.
• The servlet container loads the servlet before invoking the service() method.
• Then the servlet container handles multiple requests by spawning multiple threads, each
thread executing the service() method of a single instance of the servlet.
Servlets are Java classes which service HTTP requests and implement the javax.servlet.Servlet
interface. Web application developers typically write servlets that extend
javax.servlet.http.HttpServlet, an abstract class that implements the Servlet interface and is
specially designed to handle HTTP requests.
Sample Code
Following is the samp le source code structure of a servlet example to show Hello World −
Page 5 of 36
Servlet Notes Advanced Java Programming
Compiling a Servlet
Let us create a file with name HelloWorld.java with the code shown above. Place this file at
C:\ServletDevel (in Windows) or at /usr/ServletDevel (in Unix). This path location must be
added to CLASSPATH before proceeding further.
$ javac HelloWorld.java
If the servlet depends on any other libraries, you have to include those JAR files on your
CLASSPATH as well. I have included only servlet-api.jar JAR file because I'm not using any
other library in Hello World program.
This command line uses the built-in javac compiler that comes with the Sun Microsystems Java
Software Development Kit (JDK). For this command to work properly, you have to include the
location of the Java SDK that you are using in the PATH environment variable.
If everything goes fine, above compilation would produce HelloWorld.class file in the same
directory. Next section would explain how a compiled servlet would be deployed in production.
Page 6 of 36
Servlet Notes Advanced Java Programming
Servlet Deployment
By default, a servlet application is located at the path <Tomcat-installationdirectory>/webapps/
ROOT and the class file would reside in <Tomcat-installationdirectory> /webapps/ ROOT/
WEB-INF/classes.
If you have a fully qualified class name of com.myorg.MyServlet, then this servlet class must
be located in WEB-INF/classes/com/myorg/MyServlet.class.
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
Above entries to be created inside <web-app>...</web-app> tags available in web.xml file. There
could be various entries in this table already available, but never mind.
You are almost done, now let us start tomcat server using <Tomcat-installationdirectory> \bin\
startup.bat (on Windows) or <Tomcat-installationdirectory>/bin/startup.sh (on Linux/Solaris
etc.) and finally type http://localhost:8080/HelloWorld in the browser's address box. If
everything goes fine, you would get the following result
You must have come across many situations when you need to pass some information from your
browser to web server and ultimately to your backend program. The browser uses two methods to
pass this information to web server. These methods are GET Method and POST Method.
Page 7 of 36
Servlet Notes Advanced Java Programming
GET Method
The GET method sends the encoded user information appended to the page request. The page and
the encoded information are separated by the ? (question mark) symbol as follows −
The GET method is the default method to pass information from browser to web server and it
produces a long string that appears in your browser's Location:box. Never use the GET method if
you have password or other sensitive information to pass to the server. The GET method has size
limitation: only 1024 characters can be used in a request string.
This information is passed using QUERY_STRING header and will be accessible through
QUERY_STRING environment variable and Servlet handles this type of requests using doGet()
method.
POST Method
A generally more reliable method of passing information to a backend program is the POST
method. This packages the information in exactly the same way as GET method, but instead of
sending it as a text string after a ? (question mark) in the URL it sends it as a separate message.
This message comes to the backend program in the form of the standard input which you can parse
and use for your processing. Servlet handles this type of requests using doPost() method.
Given below is the HelloForm.java servlet program to handle input given by web browser. We
are going to use getParameter() method which makes it very easy to access passed information −
Page 8 of 36
Servlet Notes Advanced Java Programming
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<ul>\n" +
" <li><b>First Name</b>: "
+ request.getParameter("first_name") + "\n" +
" <li><b>Last Name</b>: "
+ request.getParameter("last_name") + "\n" +
"</ul>\n" +
"</body>" +
"</html>"
);
}
}
$ javac HelloForm.java
If everything goes fine, above compilation would produce HelloForm.class file. Next you would
have to copy this class file in <Tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes
and create following entries in web.xml file located in <Tomcat-installation-
directory>/webapps/ROOT/WEB-INF/
<servlet>
<servlet-name>HelloForm</servlet-name>
<servlet-class>HelloForm</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloForm</servlet-name>
<url-pattern>/HelloForm</url-pattern>
</servlet-mapping>
Page 9 of 36
Servlet Notes Advanced Java Programming
<html>
<body>
<form action = "HelloForm" method = "GET">
First Name: <input type = "text" name = "first_name">
<br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
Try to enter First Name and Last Name and then click submit button to see the result on your local
machine where tomcat is running. Based on the input provided, it will generate similar result as
mentioned in the above example.
Page 10 of 36
Servlet Notes Advanced Java Programming
import javax.servlet.http.*;
response.setContentType("text/html");
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<ul>\n" +
" <li><b>First Name</b>: "
+ request.getParameter("first_name") + "\n" +
" <li><b>Last Name</b>: "
+ request.getParameter("last_name") + "\n" +
"</ul>\n" +
"</body>"
"</html>"
);
}
doGet(request, response);
}
}
Now compile and deploy the above Servlet and test it using Hello.htm with the POST method as
follows −
<html>
<body>
<form action = "HelloForm" method = "POST">
First Name: <input type = "text" name = "first_name">
<br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
Page 11 of 36
Servlet Notes Advanced Java Programming
Here is the actual output of the above form, Try to enter First and Last Name and then click submit
button to see the result on your local machine where tomcat is running.
Based on the input provided, it would generate similar result as mentioned in the above
examples.
Here is example HTML code, CheckBox.htm, for a form with two checkboxes
<html>
<body>
<form action = "CheckBox" method =
"POST" target = "_blank">
<input type = "checkbox" name =
"maths" checked = "checked" /> Maths
<input type = "checkbox" name =
"physics" /> Physics
<input type = "checkbox" name =
"chemistry" checked = "checked" />
Chemistry
<input type = "submit" value = "Select Subject" />
</form>
</body>
</html>
Given below is the CheckBox.java servlet program to handle input given by web browser for
checkbox button.
Page 12 of 36
Servlet Notes Advanced Java Programming
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<ul>\n" +
" <li><b>Maths Flag : </b>: "
+ request.getParameter("maths") + "\n" +
" <li><b>Physics Flag: </b>: "
+ request.getParameter("physics") + "\n" +
" <li><b>Chemistry Flag: </b>: "
+ request.getParameter("chemistry") + "\n" +
"</ul>\n" +
"</body>"
"</html>"
);
}
doGet(request, response);
}
}
Once we have an Enumeration, we can loop down the Enumeration in standard way by, using
hasMoreElements() method to determine when to stop and using nextElement() method to get each
parameter name.
Page 13 of 36
Servlet Notes Advanced Java Programming
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<table width = \"100%\" border = \"1\" align = \"center\">\n" +
"<tr bgcolor = \"#949494\">\n" +
"<th>Param Name</th>"
"<th>Param Value(s)</th>\n"+
"</tr>\n"
);
while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.print("<tr><td>" + paramName + "</td>\n<td>");
String[] paramValues = request.getParameterValues(paramName);
Page 14 of 36
Servlet Notes Advanced Java Programming
out.println("</tr>\n</table>\n</body></html>");
}
doGet(request, response);
}
}
<html>
<body>
<form action = "ReadParams" method = "POST" target = "_blank">
<input type = "checkbox" name = "maths" checked = "checked" /> Maths
<input type = "checkbox" name = "physics" /> Physics
<input type = "checkbox" name = "chemistry" checked = "checked" />
Chem
<input type = "submit" value = "Select Subject" />
</form>
</body>
</html>
Now calling servlet using the above form would generate the following result −
maths on
chemistry on
You can try the above servlet to read any other form's data having other objects like text box,
radio button or drop down box etc.
Page 15 of 36
Servlet Notes Advanced Java Programming
Once we have an Enumeration, we can loop down the Enumeration in the standard manner, using
hasMoreElements() method to determine when to stop and using nextElement() method to get each
parameter name
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n"+
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<table width = \"100%\" border = \"1\" align = \"center\">\n" +
"<tr bgcolor = \"#949494\">\n" +
"<th>Header Name</th><th>Header Value(s)</th>\n"+
"</tr>\n"
);
while(headerNames.hasMoreElements()) {
String paramName = (String)headerNames.nextElement();
out.print("<tr><td>" + paramName + "</td>\n");
String paramValue = request.getHeader(paramName);
out.println("<td> " + paramValue + "</td></tr>\n");
}
out.println("</table>\n</body></html>");
}
Page 16 of 36
Servlet Notes Advanced Java Programming
doGet(request, response);
}
}
Now calling the above servlet would generate the following result −
accept */*
accept-language en-us
Host localhost:8080
Connection Keep-Alive
cache-control no-cache
Page 17 of 36
Servlet Notes Advanced Java Programming
if(calendar.get(Calendar.AM_PM) == 0)
am_pm = "AM";
else
am_pm = "PM";
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"
);
}
doGet(request, response);
}
}
Now calling the above servlet would display current system time after every 5 seconds as
follows. Just run the servlet and wait to see the result −
Page 18 of 36
Servlet Notes Advanced Java Programming
Cookies
Cookies are text files stored on the client computer and they are kept for various information
tracking purpose. Java Servlets transparently supports HTTP cookies.
• Server script sends a set of cookies to the browser. For example name, age, or identification
number etc.
• Browser stores this information on local machine for future use.
• When next time browser sends any request to web server then it sends those cookies
information to the server and server uses that information to identify the user.
(1) Creating a Cookie object − You call the Cookie constructor with a cookie name and a
cookie value, both of which are strings.
Keep in mind, neither the name nor the value should contain white space or any of the following
characters −
[ ] ( ) = , " / ? @ : ;
(2) Setting the maximum age − You use setMaxAge to specify how long (in seconds) the
cookie should be valid. Following would set up a cookie for 24 hours.
cookie.setMaxAge(60 * 60 * 24);
(3) Sending the Cookie into the HTTP response headers − You use response.addCookie to
add cookies in the HTTP response header as follows −
response.addCookie(cookie);
Let us modify our Form Example to set the cookies for first and last name.
Page 19 of 36
Servlet Notes Advanced Java Programming
out.println(docType +
"<html>\n" +
"<head>
<title>" + title + "</title>
</head>\n" +
Compile the above servlet HelloForm and create appropriate entry in web.xml file and finally
try following HTML page to call servlet.
<html>
<body>
<form action = "HelloForm" method = "GET">
First Name: <input type = "text" name = "first_name">
<br />
Page 20 of 36
Servlet Notes Advanced Java Programming
First Name:
Last Name:
Try to enter First Name and Last Name and then click submit button. This would display first name
and last name on your screen and same time it would set two cookies firstName and lastName
which would be passed back to the server when next time you would press Submit button.
Next section would explain you how you would access these cookies back in your web application.
Example
Page 21 of 36
Servlet Notes Advanced Java Programming
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" );
Compile above servlet ReadCookies and create appropriate entry in web.xml file. If you would
have set first_name cookie as "John" and last_name cookie as "Player" then running
http://localhost:8080/ReadCookies would display the following result −
Page 22 of 36
Servlet Notes Advanced Java Programming
Example
The following example would delete and existing cookie named "first_name" and when you
would run ReadCookies servlet next time it would return null value for first_name.
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" );
if((cookie.getName( )).compareTo("first_name") == 0 ) {
cookie.setMaxAge(0);
response.addCookie(cookie);
out.print("Deleted cookie : " + cookie.getName( ) + "<br/>");
}
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( )+" <br/>");
}
} else {
out.println("<h2>No cookies founds</h2>");
}
out.println("</body>");
Page 23 of 36
Servlet Notes Advanced Java Programming
out.println("</html>");
}
}
Compile above servlet DeleteCookies and create appropriate entry in web.xml file. Now running
http://localhost:8080/DeleteCookies would display the following result −
Now try to run http://localhost:8080/ReadCookies and it would display only one cookie as
follows −
You can delete your cookies in Internet Explorer manually. Start at the Tools menu and select
Internet Options. To delete all cookies, press Delete Cookies.
Session Management
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 −
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 not support a cookie, so I would
not recommend to use this procedure to maintain the sessions.
Page 24 of 36
Servlet Notes Advanced Java Programming
A web server can send a hidden HTML form field along with a unique session ID as follows −
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.
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.
URL rewriting is a better way to maintain sessions and it works even when browsers don't support
cookies. The drawback of URL re-writing is that you would have to generate every URL
dynamically to assign a session ID, even in case of a simple static HTML page.
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 −
Page 25 of 36
Servlet Notes Advanced Java Programming
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
Page 26 of 36
Servlet Notes Advanced Java Programming
</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 the above servlet SessionTrack and create appropriate entry in web.xml file. Now
running http://localhost:8080/SessionTrack would display the following result when you would
run for the first time −
Welcome to my website
Session Infomation
id 0AE3EC93FF44E3C525B4351B77ABB2D5
Page 27 of 36
Servlet Notes Advanced Java Programming
User ID ABCD
Number of visits 0
Now try to run the same servlet for second time, it would display following result.
Session Infomation
id 0AE3EC93FF44E3C525B4351B77ABB2D5
User ID ABCD
Number of visits 1
• 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.
Page 28 of 36
Servlet Notes Advanced Java Programming
<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.
Page Redirection
Page redirection is a technique where the client is sent to a new location other than requested. Page
redirection is generally used when a document moves to a new location or may be because of load
balancing.
The simplest way of redirecting a request to another page is using method sendRedirect() of
response object. Following is the signature of this method −
This method sends back the response to the browser along with the status code and new page
location. You can also use setStatus() and setHeader() methods together to achieve the same −
....
String site = "http://www.newpage.com" ;
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site);
....
Example
This example shows how a servlet performs page redirection to another location −
import java.io.*;
import java.sql.Date;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
Page 29 of 36
Servlet Notes Advanced Java Programming
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site);
}
}
Now let us compile above servlet and create following entries in web.xml
....
<servlet>
<servlet-name>PageRedirect</servlet-name>
<servlet-class>PageRedirect</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PageRedirect</servlet-name>
<url-pattern>/PageRedirect</url-pattern>
</servlet-mapping>
....
Now call this servlet using URL http://localhost:8080/PageRedirect. This would redirect you to
URL http://www.photofuntoos.com.
Following are the steps to be taken to implement a simple page hit counter which is based on
Servlet Life Cycle −
Here I'm assuming that the web container will not be restarted. If it is restarted or servlet
destroyed, the hit counter will be reset.
Page 30 of 36
Servlet Notes Advanced Java Programming
Example
import java.io.*;
import java.sql.Date;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<h2 align = \"center\">" + hitCount + "</h2>\n" +
"</body>
</html>"
);
}
Now let us compile above servlet and create following entries in web.xml
<servlet>
<servlet-name>PageHitCounter</servlet-name>
Page 31 of 36
Servlet Notes Advanced Java Programming
<servlet-class>PageHitCounter</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PageHitCounter</servlet-name>
<url-pattern>/PageHitCounter</url-pattern>
</servlet-mapping>
....
Now call this servlet using URL http://localhost:8080/PageHitCounter. This would increase
counter by one every time this page gets refreshed and it would display following result −
6
Hit Counter for a Website:
Many times you would be interested in knowing total number of hits on your whole website. This
is also very simple in Servlet and we can achieve this using filters.
Following are the steps to be taken to implement a simple website hit counter which is based on
Filter Life Cycle −
Here I'm assuming that the web container will not be restarted. If it is restarted or servlet
destroyed, the hit counter will be reset.
Example
Page 32 of 36
Servlet Notes Advanced Java Programming
Now let us compile the above servlet and create the following entries in web.xml
....
<filter>
<filter-name>SiteHitCounter</filter-name>
<filter-class>SiteHitCounter</filter-class>
</filter>
<filter-mapping>
<filter-name>SiteHitCounter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
....
Now call any URL like URL http://localhost:8080/. This would increase counter by one every
time any page gets a hit and it would display following message in the log −
Page 33 of 36
Servlet Notes Advanced Java Programming
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 −
This method sends back header "Refresh" to the browser along with an integer value which
indicates time interval in seconds.
Example
This example shows how a servlet performs auto page refresh using setIntHeader() method to
set Refresh header.
if(calendar.get(Calendar.AM_PM) == 0)
am_pm = "AM";
else
am_pm = "PM";
Page 34 of 36
Servlet Notes Advanced Java Programming
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"
);
}
doGet(request, response);
}
}
Now let us compile the above servlet and create the 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 −
Page 35 of 36
Servlet Notes Advanced Java Programming
Annotations
So far, you have learnt how Servlet uses the deployment descriptor (web.xml file) for deploying
your application into a web server. Servlet API 3.0 has introduced a new package called
javax.servlet.annotation. It provides annotation types which can be used for annotating a servlet
class. If you use annotation, then the deployment descriptor (web.xml) is not required. But you
should use tomcat7 or any later version of tomcat. Annotations can replace equivalent XML
configuration in the web deployment descriptor file (web.xml) such as servlet declaration and
servlet mapping. Servlet containers will process the annotated classes at deployment time.
@WebServlet
The @WebServlet is used to declare the configuration of a Servlet with a container.
The following example describes how to use @WebServlet annotation. It is a simple servlet that
displays the text Hello Servlet.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(value = "/Simple")
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<html><body>");
out.print("<h3>Hello Servlet</h3>");
out.print("</body></html>");
} }
Compile Simple.java in the usual way and put your class file in <Tomcat-installationdirectory>/
webapps/ROOT /WEB-INF/classes.
Now try to call any servlet by just running http://localhost:8080/Simple. You will see the following
output on the web page.
Hello servlet
Page 36 of 36