Académique Documents
Professionnel Documents
Culture Documents
Servlet Filters are Java classes that can be used in Servlet Programming for the following purposes:
To intercept requests from a client before they access a resource at back end.
To manipulate responses from server before they are sent back to the client.
Authentication Filters.
Data compression Filters.
Encryption Filters.
Filters that trigger resource access events.
Image Conversion Filters.
Logging and Auditing Filters.
MIME-TYPE Chain Filters.
Tokenizing Filters .
XSL/T Filters That Transform XML Content.
Filters are deployed in the deployment descriptor file web.xml and then map to either servlet names or URL patterns in
your application's deployment descriptor.
When the web container starts up your web application, it creates an instance of each filter that you have declared in the
deployment descriptor. The filters execute in the order that they are declared in the deployment descriptor.
throws ServletException{
// Get init parameter
String testParam = config.getInitParameter("test-param");
//Print the init parameter
System.out.println("Test Param: " + testParam);
}
public void
doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws java.io.IOException, ServletException {
Compile LogFilter.java in usual way and put your class file in <Tomcat-installation-directory>/webapps/ROOT/WEBINF/classes.
The above filter would apply to all the servlets because we specified /* in our configuration. You can specicy a particular
servlet path if you want to apply filter on few servlets only.
Now try to call any servlet in usual way and you would see generated log in your web server log. You can use Log4J
logger to log above log in a separate file.
<filter-name>LogFilter</filter-name>
<filter-class>LogFilter</filter-class>
<init-param>
<param-name>test-param</param-name>
<param-value>Initialization Paramter</param-value>
</init-param>
</filter>
<filter>
<filter-name>AuthenFilter</filter-name>
<filter-class>AuthenFilter</filter-class>
<init-param>
<param-name>test-param</param-name>
<param-value>Initialization Paramter</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>LogFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>AuthenFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Servlet Exception
When a servlet throws an exception, the web container searches the configurations in web.xml that use the exception-type
element for a match with the thrown exception type.
You would have to use the error-page element in web.xml to specify the invocation of servlets in response to certain
exceptions or HTTP status codes.
web.xml Configuration:
Consider, you have an ErrorHandler servlet which would be called whenever there is any defined exception or error.
Following would be the entry created in web.xml.
<!-- servlet definition -->
<servlet>
<servlet-name>ErrorHandler</servlet-name>
<servlet-class>ErrorHandler</servlet-class>
</servlet>
<!-- servlet mappings -->
<servlet-mapping>
<servlet-name>ErrorHandler</servlet-name>
<url-pattern>/ErrorHandler</url-pattern>
</servlet-mapping>
<!-- error-code related error pages -->
<error-page>
<error-code>404</error-code>
<location>/ErrorHandler</location>
</error-page>
<error-page>
<error-code>403</error-code>
<location>/ErrorHandler</location>
</error-page>
<!-- exception-type related error pages -->
<error-page>
<exception-type>
javax.servlet.ServletException
</exception-type >
<location>/ErrorHandler</location>
</error-page>
<error-page>
<exception-type>java.io.IOException</exception-type >
<location>/ErrorHandler</location>
</error-page>
If you want to have a generic Error Handler for all the exceptions then you should define following error-page instead of
defining separate error-page elements for every exception:
<error-page>
<exception-type>java.lang.Throwable</exception-type >
<location>/ErrorHandler</location>
</error-page>
Following are the points to be noted about above web.xml for Exception Handling:
The servlet ErrorHandler is defined in usual way as any other servlet and configured in web.xml.
If there is any error with status code either 404 ( Not Found) or 403 ( Forbidden ), then ErrorHandler servlet
would be called.
If the web application throws either ServletException or IOException, then the web container invokes the
/ErrorHandler servlet.
You can define different Error Handlers to handle different type of errors or exceptions. Above example is very
much generic and hope it serve the purpose to explain you the basic concept.
5
6
javax.servlet.error.request_uri
This attribute gives information about URL calling the servlet and it can be stored and analysed after storing in a
java.lang.String data type.
javax.servlet.error.exception
This attribute gives information the exception raised which can be stored and analysed after storing in a
java.lang.Throwable data type.
javax.servlet.error.servlet_name
This attribute gives servlet name which can be stored and analysed after storing in a java.lang.String data type.
"\">Home Page</a>.");
}else if (statusCode != null){
out.println("The status code : " + statusCode);
}else{
out.println("<h2>Error information</h2>");
out.println("Servlet Name : " + servletName +
"</br></br>");
out.println("Exception Type : " +
throwable.getClass( ).getName( ) +
"</br></br>");
out.println("The request URI: " + requestUri +
"<br><br>");
out.println("The exception message: " +
throwable.getMessage( ));
}
out.println("</body>");
out.println("</html>");
}
// Method to handle POST method request.
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Compile ErrorHandler.java in usual way and put your class file in <Tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes.
Let us add the following configuration in web.xml to handle exceptions:
<servlet>
<servlet-name>ErrorHandler</servlet-name>
<servlet-class>ErrorHandler</servlet-class>
</servlet>
<!-- servlet mappings -->
<servlet-mapping>
<servlet-name>ErrorHandler</servlet-name>
<url-pattern>/ErrorHandler</url-pattern>
</servlet-mapping>
<error-page>
<error-code>404</error-code>
<location>/ErrorHandler</location>
</error-page>
<error-page>
<exception-type>java.lang.Throwable</exception-type >
<location>/ErrorHandler</location>
</error-page>
Now try to use a servlet which raise any exception or type a wrong URL, this would trigger Web Container to call
ErrorHandler servlet and display an appropriate message as programmed. For example, if you type a wrong URL then it
would display the following result:
The status code : 404
Above code may not work with some web browsers. So try with Mozilla and Safari and it should work.
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.
There are three steps involved in identifying returning users:
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.
This chapter will teach you how to set or reset cookies, how to access them and how to delete them.
As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a domain. The name and value
will be URL encoded. The expires field is an instruction to the browser to "forget" the cookie after the given time and
date.
If the browser is configured to store cookies, it will then keep this information until the expiry date. If the user points the
browser at any page that matches the path and domain of the cookie, it will resend the cookie to the server. The browser's
headers might look something like this:
GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)
Host: zink.demon.co.uk:1126
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name=xyz
A servlet will then have access to the cookie through the request method request.getCookies() which returns an array of
Cookie objects.
5
6
7
8
9
10
11
12
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);
Example:
Let us modify our Form Example to set the cookies for first and last name.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloForm extends HttpServlet {
Compile 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 />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Keep above HTML content in a file Hello.htm and put it in <Tomcat-installation-directory>/webapps/ROOT directory.
When you would access http://localhost:8080/Hello.htm, here is the actual output of the above form.
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:
Let us read cookies which we have set in previous example:
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class ReadCookies extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
Cookie cookie = null;
Cookie[] cookies = null;
// Get an array of Cookies associated with this domain
cookies = request.getCookies();
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Reading Cookies Example";
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" );
if( cookies != null ){
out.println("<h2> Found Cookies Name and Value</h2>");
for (int i = 0; i < cookies.length; i++){
cookie = cookies[i];
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( )+" <br/>");
}
}else{
out.println(
"<h2>No cookies founds</h2>");
}
out.println("</body>");
out.println("</html>");
}
}
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:
Example:
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.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class DeleteCookies extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
Cookie cookie = null;
Cookie[] cookies = null;
// Get an array of Cookies associated with this domain
cookies = request.getCookies();
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Delete Cookies Example";
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" );
if( cookies != null ){
out.println("<h2> Cookies Name and Value</h2>");
for (int i = 0; i < cookies.length; i++){
cookie = cookies[i];
if((cookie.getName( )).compareTo("first_name") == 0 ){
cookie.setMaxAge(0);
response.addCookie(cookie);
out.print("Deleted cookie : " +
cookie.getName( ) + "<br/>");
}
Compile above servlet DeleteCookies and create appropriate entry in web.xml file. Now running
http://localhost:8080/DeleteCookies would display the following result:
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:
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.
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.
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.
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.
10
11
session.setAttribute(visitCountKey,
visitCount);
Compile 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
Session info
value
id
0AE3EC93FF44E3C525B4351B77ABB2D5
Creation Time
ABCD
Number of visits
Now try to run the same servlet for second time, it would display following result.
Session Infomation
info type
value
id
0AE3EC93FF44E3C525B4351B77ABB2D5
Creation Time
ABCD
Number of visits
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.
Servlet JDBC
This tutorial assumes you have understanding on how JDBC application works. Before starting with database access
through a servlet, make sure you have proper JDBC environment setup along with a database.
For more detail on how to access database using JDBC and its environment setup you can go through our JDBC Tutorial.
To start with basic concept, let us create a simple table and create few records in that table as follows:
Create Table
To create the Employees table in TEST database, use the following steps:
Step 1:
Open a Command Prompt and change to the installation directory as follows:
C:\>
C:\>cd Program Files\MySQL\bin
C:\Program Files\MySQL\bin>
Step 2:
Login to database as follows
C:\Program Files\MySQL\bin>mysql -u root -p
Enter password: ********
mysql>
Step 3:
Create the table Employee in TEST database as follows:
mysql> use TEST;
mysql> create table Employees
(
id int not null,
age int not null,
first varchar (255),
last varchar (255)
);
Query OK, 0 rows affected (0.08 sec)
mysql>
Accessing a Database:
Here is an example which shows how to access TEST database using Servlet.
// Loading required libraries
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class DatabaseAccess extends HttpServlet{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// JDBC driver name and database URL
static final String JDBC_DRIVER="com.mysql.jdbc.Driver";
static final String DB_URL="jdbc:mysql://localhost/TEST";
// Database credentials
static final String USER = "root";
static final String PASS = "password";
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Database Result";
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");
try{
// Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Open a connection
conn = DriverManager.getConnection(DB_URL,USER,PASS);
// Execute SQL query
stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
// Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
out.println("ID: " + id + "<br>");
out.println(", Age: " + age + "<br>");
out.println(", First: " + first + "<br>");
out.println(", Last: " + last + "<br>");
}
out.println("</body></html>");
// Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
} //end try
}
}
Now let us compile above servlet and create following entries in web.xml
....
<servlet>
<servlet-name>DatabaseAccess</servlet-name>
<servlet-class>DatabaseAccess</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DatabaseAccess</servlet-name>
<url-pattern>/DatabaseAccess</url-pattern>
</servlet-mapping>
....
Now call this servlet using URL http://localhost:8080/DatabaseAccess which would display following response:
Database Result
ID:
ID:
ID:
ID:
100,
101,
102,
103,
Age:
Age:
Age:
Age:
18,
25,
30,
28,
First:
First:
First:
First:
File Upload
A Servlet can be used with an HTML form tag to allow users to upload files to the server. An uploaded file could be a text
file or image file or any document.
The form method attribute should be set to POST method and GET method can not be used.
The form enctype attribute should be set to multipart/form-data.
The form action attribute should be set to a servlet file which would handle file uploading at backend server.
Following example is using UploadServlet servlet to upload file.
To upload a single file you should use a single <input .../> tag with attribute type="file". To allow multiple files
uploading, include more than one input tags with different values for the name attribute. The browser associates a
Browse button with each of them.
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="UploadServlet" method="post"
enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>
This will display following result which would allow to select a file from local PC and when user would click at "Upload
File", form would be submitted along with the selected file:
File Upload:
Select a file to upload:
Following is the source code for UploadServlet which can handle multiple file uploading at a time. Before procedding you
have make sure the followings:
Following example depends on FileUpload, so make sure you have the latest version of commonsfileupload.x.x.jar file in your classpath. You can download it from http://commons.apache.org/fileupload/.
FileUpload depends on Commons IO, so make sure you have the latest version of commons-io-x.x.jar file in
your classpath. You can download it from http://commons.apache.org/io/.
While testing following example, you should upload a file which has less size than maxFileSize otherwise file
would not be uploaded.
Make sure you have created directories c:\temp and c:\apache-tomcat-5.5.29\webapps\data well in advance.
javax.servlet.ServletConfig;
javax.servlet.ServletException;
javax.servlet.http.HttpServlet;
javax.servlet.http.HttpServletRequest;
javax.servlet.http.HttpServletResponse;
import
import
import
import
import
org.apache.commons.fileupload.FileItem;
org.apache.commons.fileupload.FileUploadException;
org.apache.commons.fileupload.disk.DiskFileItemFactory;
org.apache.commons.fileupload.servlet.ServletFileUpload;
org.apache.commons.io.output.*;
boolean isMultipart;
String filePath;
int maxFileSize = 50 * 1024;
int maxMemSize = 4 * 1024;
File file ;
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String fileName = fi.getName();
String contentType = fi.getContentType();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 ){
file = new File( filePath +
fileName.substring( fileName.lastIndexOf("\\"))) ;
}else{
file = new File( filePath +
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write( file ) ;
out.println("Uploaded Filename: " + fileName + "<br>");
}
}
out.println("</body>");
out.println("</html>");
}catch(Exception ex) {
System.out.println(ex);
}
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException {
throw new ServletException("GET method used with " +
getClass( ).getName( )+": POST method required.");
}
}
Now try to upload files using the HTML form which you created above. When you would try
http://localhost:8080/UploadFile.htm, it would display following result which would help you uploading any file from
your local machine.
File Upload:
Select a file to upload:
If your servelt script works fine, your file should be uploaded in c:\apache-tomcat-5.5.29\webapps\data\ directory.
One of the most important advantages of using Servlet is that you can use most of the methods available in core Java. This
tutorial would take you through Java provided Date class which is available in java.util package, this class encapsulates
the current date and time.
The Date class supports two constructors. The first constructor initializes the object with the current date and time.
Date( )
The following constructor accepts one argument that equals the number of milliseconds that have elapsed since midnight,
January 1, 1970
Date(long millisec)
Once you have a Date object available, you can call any of the following support methods to play with dates:
SN
Object clone( )
Duplicates the invoking Date object.
long getTime( )
Returns the number of milliseconds that have elapsed since January 1, 1970.
int hashCode( )
Returns a hash code for the invoking object.
String toString( )
Converts the invoking Date object into a string and returns the result.
10
Now let us compile above servlet and create appropriate entries in web.xml and then call this servlet using URL
http://localhost:8080/CurrentDate. This would produce following result:
Date Comparison:
As I mentioned above you can use all the available Java methods in your Servlet. In case you need to compare two dates,
following are the methods:
You can use getTime( ) to obtain the number of milliseconds that have elapsed since midnight, January 1, 1970,
for both objects and then compare these two values.
You can use the methods before( ), after( ), and equals( ). Because the 12th of the month comes before the 18th,
for example, new Date(99, 2, 12).before(new Date (99, 2, 18)) returns true.
You can use the compareTo( ) method, which is defined by the Comparable interface and implemented by Date.
Compile above servlet once again and then call this servlet using URL http://localhost:8080/CurrentDate. This would
produce following result:
To specify the time format use a time pattern string. In this pattern, all ASCII letters are reserved as pattern letters, which
are defined as the following:
Character
Description
Example
Era designator
AD
2001
Month in year
July or 07
Day in month
10
12
22
Minute in hour
30
Second in minute
55
Millisecond
234
Day in week
Tuesday
Day in year
360
Week in year
40
Week in month
A.M./P.M. marker
PM
24
10
Time zone
'
Delimiter
"
Single quote
For a complete list of constant available methods to manipulate date, you can refer to standard Java documentation.
Page redirection
Page redirection is generally used when a document moves to a new location and we need to send the client to this new
location or may be because of load balancing, or for simple randomization.
The simplest way of redirecting a request to another page is using method sendRedirect() of response object. Following
is the signature of this method:
public void HttpServletResponse.sendRedirect(String location)
throws IOException
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
import
import
import
import
java.io.*;
java.sql.Date;
java.util.*;
javax.servlet.*;
javax.servlet.http.*;
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 take you given URL
http://www.photofuntoos.com.
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:
This example shows how to implement a simple page hit counter:
import
import
import
import
import
java.io.*;
java.sql.Date;
java.util.*;
javax.servlet.*;
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>");
}
public void destroy()
{
// This is optional step but if you like you
// can write hitCount value in your database.
}
}
Now let us compile above servlet and create following entries in web.xml
....
<servlet>
<servlet-name>PageHitCounter</servlet-name>
<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:
This example shows how to implement a simple website hit counter:
init(FilterConfig config)
throws ServletException{
// Reset hit counter.
hitCount = 0;
}
public void
doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws java.io.IOException, ServletException {
Now let us compile above servlet and create 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:
Site visits count :
Site visits count :
Site visits count :
Site visits count :
Site visits count :
..................
1
2
3
4
5
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.
}
}
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:
The web application structure involving the WEB-INF subdirectory is standard to all Java web applications and specified
by the servlet API specification. Given a top-level directory name of myapp, Here is what this directory structure looks
like:
/myapp
/images
/WEB-INF
/classes
/lib
The WEB-INF subdirectory contains the application's deployment descriptor, named web.xml. All the HTML files live in
the top-level directory which is myapp. For admin user, you would find ROOT directory as parent directory as myapp.
Following is the example to create MyServlet class with a package name com.myorg
// Name your package
package com.myorg;
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet {
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 MyServlet.class file in the same directory. Next section would
explain how a compiled servlet would be deployed in production.
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet</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-installation-directory>\bin\startup.bat (on windows) or
<Tomcat-installation-directory>/bin/startup.sh (on Linux/Solaris etc.) and finally type http://localhost:8080/MyServlet
in browser's address box. If everything goes fine, you would get following result:
It is always difficult to testing/debugging a servlets. Servlets tend to involve a large amount of client/server interaction,
making errors likely but hard to reproduce.
Here are a few hints and suggestions that may aid you in your debugging.
System.out.println()
System.out.println() is easy to use as a marker to test whether a certain piece of code is being executed or not. We can
print out variable values as well. Additionally:
Since the System object is part of the core Java objects, it can be used everywhere without the need to install any
extra classes. This includes Servlets, JSP, RMI, EJB's, ordinary Beans and classes, and standalone applications.
Compared to stopping at breakpoints, writing to System.out doesn't interfere much with the normal execution
flow of the application, which makes it very valuable when timing is crucial.
All the messages generated by above syntax would be logged in web server log file.
Message Logging:
It is always great idea to use proper logging method to log all the debug, warning and error messages using a standard
logging method. I use log4J to log all the messages.
The Servlet API also provides a simple way of outputting information by using the log() method as follows:
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ContextLog extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
java.io.IOException {
String par = request.getParameter("par1");
//Call the two ServletContext.log methods
ServletContext context = getServletContext( );
if (par == null || par.equals(""))
//log version with Throwable parameter
The ServletContext logs its text messages to the servlet container's log file. With Tomcat these logs are found in <Tomcatinstallation-directory>/logs.
The log files do give an indication of new emerging bugs or the frequency of problems. For that reason it's good to use the
log() function in the catch clause of exceptions which should normally not occur.
Set your debugger's classpath so that it can find sun.servlet.http.Http-Server and associated classes.
Set your debugger's classpath so that it can also find your servlets and support classes, typically
server_root/servlets and server_root/classes.
You normally wouldn't want server_root/servlets in your classpath because it disables servlet reloading. This inclusion,
however, is useful for debugging. It allows your debugger to set breakpoints in a servlet before the custom servlet loader
in HttpServer loads the servlet.
Once you have set the proper classpath, start debugging sun.servlet.http.HttpServer. You can set breakpoints in whatever
servlet you're interested in debugging, then use a web browser to make a request to the HttpServer for the given servlet
(http://localhost:8080/servlet/ServletToDebug). You should see execution stop at your breakpoints.
Using Comments:
Comments in your code can help the debugging process in various ways. Comments can be used in lots of other ways in
the debugging process.
The Servlet uses Java comments and single line (// ...) and multiple line (/* ... */) comments can be used to temporarily
remove parts of your Java code. If the bug disappears, take a closer look at the code you just commented and find out the
problem.
Be aware that server_root/classes doesn't reload and that server_root/servlets probably does.
Ask a browser to show the raw content of the page it is displaying. This can help identify formatting problems. It's
usually an option under the View menu.
Make sure the browser isn't caching a previous request's output by forcing a full reload of the page. With
Netscape Navigator, use Shift-Reload; with Internet Explorer use Shift-Refresh.
Verify that your servlet's init() method takes a ServletConfig parameter and calls super.init(config) right away.