JavaServlet Material
JavaServlet Material
JavaServlet Material
Java Servlets are programs that run on a Web or Application server and act as a
middle layer between a requests coming from a Web browser or other HTTP client
and databases or applications on the HTTP server.
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.
• Performance is significantly better.
• Servlets execute within the address space of a Web server. It is not necessary
to create a separate process to handle each client request.
• Servlets are platform-independent because they are written in Java.
• Java security manager on the server enforces a set of restrictions to protect
the resources on a server machine. So servlets are trusted.
• The full functionality of the Java class libraries is available to a servlet. It can
communicate with applets, databases, or other software via the sockets and
RMI mechanisms that you have seen already.
Servlets Architecture
The following diagram shows the position of Servlets in a Web Application.
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.
These classes implement the Java Servlet and JSP specifications. At the time of
writing this tutorial, the versions are Java Servlet 2.5 and JSP 2.1.
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.
A servlet life cycle can be defined as the entire process from its creation till the
destruction. The following are the paths followed by a servlet.
• The servlet is initialized by calling the init() method.
• The servlet calls service() method to process a client's request.
• The servlet is terminated by calling the destroy() method.
• Finally, servlet is garbage collected by the garbage collector of the JVM.
Now let us discuss the life cycle methods in detail.
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.
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 sample source code structure of a servlet example to show Hello
World −
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
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.
Assuming your environment is setup properly, go in ServletDevel directory and
compile HelloWorld.java as follows −
$ 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.
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.
For now, let us copy HelloWorld.class into <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>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
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.
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 −
http://www.test.com/hello?key1 = value1&key2 = value2
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 −
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
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>
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.
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>
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.
Given below is the CheckBox.java servlet program to handle input given by web
browser for checkbox button.
// Import required java libraries
import java.io.*;
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" +
"<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);
}
}
• Maths Flag : : on
• Chemistry Flag: : on
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);
doGet(request, response);
}
}
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.
Accept
1
This header specifies the MIME types that the browser or other clients can handle.
Values of image/png or image/jpeg are the two most common possibilities.
Accept-Charset
2
This header specifies the character sets the browser can use to display the
information. For example ISO-8859-1.
Accept-Encoding
3
This header specifies the types of encodings that the browser knows how to handle.
Values of gzip or compress are the two most common possibilities.
Accept-Language
4
This header specifies the client's preferred languages in case the servlet can
produce results in more than one language. For example en, en-us, ru, etc
Authorization
5
This header is used by clients to identify themselves when accessing password-
protected Web pages.
Connection
This header indicates whether the client can handle persistent HTTP connections.
6
Persistent connections permit the client or other browser to retrieve multiple files
with a single request. A value of Keep-Alive means that persistent connections
should be used.
Content-Length
7
This header is applicable only to POST requests and gives the size of the POST
data in bytes.
Cookie
8
This header returns cookies to servers that previously sent them to the browser.
9 Host
This header specifies the host and port as given in the original URL.
If-Modified-Since
10 This header indicates that the client wants the page only if it has been changed
after the specified date. The server sends a code, 304 which means Not
Modified header if no newer result is available.
If-Unmodified-Since
11
This header is the reverse of If-Modified-Since; it specifies that the operation should
succeed only if the document is older than the specified date.
Referer
12 This header indicates the URL of the referring Web page. For example, if you are
at Web page 1 and click on a link to Web page 2, the URL of Web page 1 is included
in the Referrer header when the browser requests Web page 2.
User-Agent
13
This header identifies the browser or other client making the request and can be
used to return different content to different types of browsers.
Cookie[] getCookies()
1
Returns an array containing all of the Cookie objects the client sent with this
request.
Enumeration getAttributeNames()
2
Returns an Enumeration containing the names of the attributes available to this
request.
Enumeration getHeaderNames()
3
Returns an enumeration of all the header names this request contains.
Enumeration getParameterNames()
4
Returns an Enumeration of String objects containing the names of the parameters
contained in this request
HttpSession getSession()
5
Returns the current session associated with this request, or if the request does not
have a session, creates one.
Locale getLocale()
7
Returns the preferred Locale that the client will accept content in, based on the
Accept-Language header.
ServletInputStream getInputStream()
9
Retrieves the body of the request as binary data using a ServletInputStream.
String getAuthType()
10
Returns the name of the authentication scheme used to protect the servlet, for
example, "BASIC" or "SSL," or null if the JSP was not protected.
String getCharacterEncoding()
11
Returns the name of the character encoding used in the body of this request.
String getContentType()
12
Returns the MIME type of the body of the request, or null if the type is not known.
String getContextPath()
13
Returns the portion of the request URI that indicates the context of the request.
String getHeader(String name)
14
Returns the value of the specified request header as a String.
String getMethod()
15
Returns the name of the HTTP method with which this request was made, for
example, GET, POST, or PUT.
String getPathInfo()
17
Returns any extra path information associated with the URL the client sent when it
made this request
String getProtocol()
18
Returns the name and version of the protocol the request.
String getQueryString()
19
Returns the query string that is contained in the request URL after the path.
String getRemoteAddr()
20
Returns the Internet Protocol (IP) address of the client that sent the request.
String getRemoteHost()
21
Returns the fully qualified name of the client that sent the request.
String getRemoteUser()
22
Returns the login of the user making this request, if the user has been
authenticated, or null if the user has not been authenticated.
String getRequestURI()
23
Returns the part of this request's URL from the protocol name up to the query string
in the first line of the HTTP request.
String getRequestedSessionId()
24
Returns the session ID specified by the client.
String getServletPath()
25
Returns the part of this request's URL that calls the JSP.
boolean isSecure()
27
Returns a Boolean indicating whether this request was made using a secure
channel, such as HTTPS.
int getContentLength()
28
Returns the length, in bytes, of the request body and made available by the input
stream, or -1 if the length is not known.
int getServerPort()
30
Returns the port number on which this request was received.
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>");
}
doGet(request, response);
}
}
Now calling the above servlet would generate the following result −
HTTP Header Request Example
Header Name Header Value(s)
accept */*
accept-language en-us
host localhost:8080
connection Keep-Alive
cache-control no-cache
Allow
1
This header specifies the request methods (GET, POST, etc.) that the server
supports.
Cache-Control
This header specifies the circumstances in which the response document can
2 safely be cached. It can have values public, private or no-cache etc. Public
means document is cacheable, Private means document is for a single user and
can only be stored in private (non-shared) caches and nocache means document
should never be cached.
Connection
3 This header instructs the browser whether to use persistent in HTTP connections
or not. A value of close instructs the browser not to use persistent HTTP
connections and keepalive means using persistent connections.
Content-Disposition
4
This header lets you request that the browser ask the user to save the response to
disk in a file of the given name.
Content-Encoding
5
This header specifies the way in which the page was encoded during transmission.
Content-Language
6
This header signifies the language in which the document is written. For example
en, en-us, ru, etc
Content-Length
7
This header indicates the number of bytes in the response. This information is
needed only if the browser is using a persistent (keep-alive) HTTP connection.
Content-Type
8
This header gives the MIME (Multipurpose Internet Mail Extension) type of the
response document.
Expires
9
This header specifies the time at which the content should be considered out-of-
date and thus no longer be cached.
Last-Modified
10 This header indicates when the document was last changed. The client can then
cache the document and supply a date by an If-Modified-Since request header in
later requests.
Location
11 This header should be included with all responses that have a status code in the
300s. This notifies the browser of the document address. The browser
automatically reconnects to this location and retrieves the new document.
Refresh
12
This header specifies how soon the browser should ask for an updated page. You
can specify time in number of seconds after which a page would be refreshed.
Retry-After
13
This header can be used in conjunction with a 503 (Service Unavailable) response
to tell the client how soon it can repeat its request.
Set-Cookie
14
This header specifies a cookie associated with the page.
boolean isCommitted()
4
Returns a Boolean indicating if the response has been committed.
void flushBuffer()
9
Forces any content in the buffer to be written to the client.
void reset()
10
Clears any data that exists in the buffer as well as the status code and headers.
void resetBuffer()
11
Clears the content of the underlying buffer in the response without clearing headers
or status code.
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 −
Servlet Filters
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.
There are various types of filters suggested by the specifications −
• 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.
Compile LogFilter.java in usual way and put your class file in <Tomcat-
installationdirectory>/webapps/ROOT/WEB-INF/classes
<filter-mapping>
<filter-name>LogFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
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>
<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>