Servlets Notes
Servlets Notes
Overview
Posted by Rakesh Singh
In this servlet tutorial Java Servlets is a web technology for Java. It was the first web
technology for Java and many new web technologies have arrived since. Still, Java
Servlets are very useful, both to know, and for certain use cases.
Java Servlets are part of the Java Enterprise Edition (Java EE). You will need to run
your Java Servlets inside a Servlet compatible "Servlet Container" (e.g. web server) in
order for them to work.
Java Servlets it Java technology for creating the dynamic web applications. Java
Servlets are server side components in Java that runs on Servlet enabled web server
such as Tomcat, Jetty, WebSphere etc.. Java Servlet is much faster then CGI and Perl
since it runs in the same JVM. In case of CGI and Perl separate memory space is
allocated for execution of the program which reduces it's performance.
Servet technology is robust and scalable as it uses the java language. Before Servlet,
CGI (Common Gateway Interface) scripting language was used as a server-side
programming language. But there were many disadvantages of this technology. We
have discussed these disadvantages below.
There are many interfaces and classes in the servlet API such
as Servlet, GenericServlet, HttpServlet, ServletRequest,ServletResponse etc.
What is a Servlet?
Servlet can be described in many ways, depending on the context.
Servlet is a technology i.e. used to create web application.
Servlet is an API that provides many interfaces and classes including
documentations.
Servlet is an interface that must be implemented for creating any servlet.
Servlet is a class that extend the capabilities of the servers and respond to the
incoming request. It can respond to any type of requests.
Servlet is a web component that is deployed on the server to create dynamic web
page.
Servlets Architecture:
Following diagram shows the position of Servelts 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.
The life cycle of a servlet is controlled by the container in which the servlet has been
deployed. When a request is mapped to a servlet, the container performs the following
steps.
If an instance of the servlet does not exist, the Web container
1. Loads the servlet class.
2. Creates an instance of the servlet class.
3. Initializes the servlet instance by calling the init method init () .
4. Invokes the service method service(), passing a request and response
object.
5. The servlet is terminated by calling the destroy() method.
6. Finally, servlet is garbage collected by the garbage collector of the JVM.
As displayed in the above diagram, there are three states of a servlet: new, ready and
end. The servlet is in new state if servlet instance is created. After invoking the init()
method, Servlet comes in the ready state. In the ready state, servlet performs all the
tasks. When the web container invokes the destroy() method, it shifts to the end state.
1) Servlet class is loaded
The classloader is responsible to load the servlet class. The servlet class is loaded
when the first request for the servlet is received by the web container.
2) Servlet instance is created
The web container creates the instance of a servlet after loading the servlet class. The
servlet instance is created only once in the servlet life cycle.
3) init method is invoked
The web container calls the init method only once after creating the servlet instance.
The init method is used to initialize the servlet. It is the life cycle method of the
javax.servlet.Servlet interface. Syntax of the init method is given below:
view plainprint?
The doGet() and doPost() are most frequently used methods with in each service
request. Here is the signature of these two methods.
The web container calls the destroy method before removing the servlet instance from
the service. It gives the servlet an opportunity to clean up any resource for example
memory, thread etc. The syntax of the destroy method of the Servlet interface is given
below:
view plainprint?
Servlet API
Posted by Rakesh Singh
The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet api.
Let's see what are the interfaces of javax.servlet package.
GenericServlet
ServletInputStream
ServletOutputStream
ServletRequestWrapper
ServletResponseWrapper
ServletRequestEvent
ServletContextEvent
ServletRequestAttributeEvent
ServletContextAttributeEvent
ServletException
UnavailableException
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.
Servlet Interface-
Servlet interface provides common behavior to all the servlets.
Servlet interface needs to be implemented for creating any servlet (either directly or
indirectly). It provides 3 life cycle methods that are used to initialize the servlet, to
service the requests, and to destroy the servlet and 2 non-life cycle methods.
Method Description
1. public void init(ServletConfig config) initializes the servlet. It is the life
cycle method of servlet and invoked by the web container only once.
2. public void service(ServletRequest request,ServletResponse
response) provides response for the incoming request. It is invoked at each
request by the web container.
3. public void destroy() is invoked only once and indicates that servlet is
being destroyed.
4. public ServletConfig getServletConfig() returns the object
of ServletConfig.
5. public String getServletInfo() returns information about servlet such as
writer, copyright, version etc.
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 C:\Program Files (x86)\Apache
Software Foundation\Tomcat 7.0\webapps\ROOT\ and the class file would reside
in C:\Program Files (x86)\Apache Software Foundation\Tomcat
7.0\webapps\ROOT\WEB-INF\classes.
<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>
Now let us start tomcat server using C:\Program Files (x86)\Apache Software
Foundation\Tomcat 7.0\bin\startup.bat (on windows) or /bin/startup.sh (on
Linux/Solaris etc.) and finally type http://localhost:8080/HelloWorld in browser's
address box. If everything goes fine, you would get following result:
What is web application servlet
Posted by Rakesh Singh
A web application is a dynamic extension of a web or application server. There are two
types of web applications:
Presentation-oriented: A presentation-oriented web application generates
interactive web pages containing various types of markup language (HTML, XML, and
so on) and dynamic content in response to requests.
Service-oriented: A service-oriented web application implements the endpoint of
a web service. Presentation-oriented applications are often clients of service-oriented
web applications.
In the Java 2 platform, web components provide the dynamic extension capabilities for
a web server. Web components are either Java servlets, JSP pages, or web service
endpoints. The interaction between a web client and a web application is illustrated in
following Figure. The client sends an HTTP request to the web server. A web server
that implements Java Servlet and JavaServer Pages technology converts the request
into an HTTPServletRequest object. This object is delivered to a web component, which
can interact with JavaBeans components or a database to generate dynamic content.
The web component can then generate an HTTPServletResponse or it can pass the
request to another web component. Eventually a web component generates a
HTTPServletResponse object. The web server converts this object to an HTTP
response and returns it to the client.
Servlets are Java programming language classes that dynamically process requests
and construct responses. JSP pages are text-based documents that execute as servlets
but allow a more natural approach to creating static content. Although servlets and JSP
pages can be used interchangeably, each has its own strengths. Servlets are best
suited for service-oriented applications (web service endpoints are implemented as
servlets) and the control functions of a presentation-oriented application, such as
dispatching requests and handling nontextual data. JSP pages are more appropriate for
generating text-based markup such as HTML, Scalable Vector Graphics (SVG),
Wireless Markup Language (WML), and XML.
Since the introduction of Java Servlet and JSP technology, additional Java technologies
and frameworks for building interactive web applications have been developed. These
technologies and their relationships are illustrated in following
Notice that Java Servlet technology is the foundation of all the web application
technologies. Each technology adds a level of abstraction that makes web application
prototyping and development faster and the web applications themselves more
maintainable, scalable, and robust.
Web components are supported by the services of a runtime platform called a web
container. A web container provides services such as request dispatching, security,
concurrency, and life-cycle management. It also gives web components access to APIs
such as naming, transactions, and email.
Certain aspects of web application behavior can be configured when the application is
installed, or deployed, to the web container. The configuration information is maintained
in a text file in XML format called a web application deployment descriptor (DD).
Using servlets web developers can create fast and efficient server side applications and
can run it on any servlet enabled web server. Servlet runs entirely inside the Java
Virtual Machine. Since the servlet runs on server side so it does not depend on browser
compatibility.
Servlets have a number of advantages over CGI and other API's. They are:
1. Platform Independence
Servlets are written entirely in java so these are platform independent. Servlets can run
on any Servlet enabled web server. For example if you develop an web application in
windows machine running Java web server, you can easily run the same on apache
web server (if Apache Serve is installed) without modification or compilation of code.
Platform independency of servlets provide a great advantages over alternatives of
servlets.
2. Performance
Due to interpreted nature of java, programs written in java are slow. But the java
servlets runs very fast. These are due to the way servlets run on web server. For any
program initialization takes significant amount of time. But in case of servlets
initialization takes place first time it receives a request and remains in memory till times
out or server shut downs. After servlet is loaded, to handle a new request it simply
creates a new thread and runs service method of servlet. In comparison to traditional
CGI scripts which creates a new process to serve the request.
3. Extensibility
Java Servlets are developed in java which is robust, well-designed and object oriented
language which can be extended or polymorphed into new objects. So the java servlets
take all these advantages and can be extended from existing class to provide the ideal
solutions.
4. Safety
Java provides very good safety features like memory management, exception handling
etc. Servlets inherits all these features and emerged as a very powerful web server
extension.
5. Secure
Servlets are server side components, so it inherits the security provided by the web
server. Servlets are also benefited with Java Security Manager.
Disadvantages of CGI
There are many problems in CGI technology:
If number of clients increases, it takes more time for sending response.
For each request, it starts a process and Web server is limited to start processes.
It uses platform dependent language e.g. C, C++, perl.
Advantage of Servlet
There are many advantages of Servlet over CGI. The web container creates threads for
handling the multiple requests to the servlet. Threads have a lot of benefits over the
Processes such as they share a common memory area, lighweight, cost of
communication between the threads are low. The basic benefits of servlet are as
follows:
1. better performance: because it creates a thread for each request not
process.
2. Portability: because it uses java language.
3. Robust: Servlets are managed by JVM so no need to worry about
momory leak, garbage collection etc.
4. Secure: because it uses java language.
Basics of Web-
There are some key points that must be known by the servlet programmer. Let's first
briefly discuss these points before starting the servlet. These are:
HTTP
HTTP Request Types
Difference between Get and Post method
Container
Server
Difference between web server and application server
Content Type
Introduction of XML
Deployment
HTTP (Hyper Text Transfer Protocol)
Http is the protocol that allows web servers and browsers to exchange data over the
web.It is a request response protocol.
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.
If everything goes fine, above compilation would produce HelloServlet.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 C:\Program Files (x86)\Apache
Software Foundation\Tomcat 7.0\webapps\ROOT\ and the class file would reside in
C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0\webapps\ROOT\WEB-
INF\classes.
For now, let us copy HelloServlet.class into /webapps/ROOT/WEB-INF/classes and
create following entries in web.xml file located in C:\Program Files (x86)\Apache
Software Foundation\Tomcat 7.0\webapps\ROOT\/webapps/ROOT/WEB-INF/
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/HelloServlet</url-pattern>
</servlet-mapping>
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
methods, but instead of sending it as a text string after a ? 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.
GenericServlet makes writing servlets easier. It provides simple versions of the lifecycle
methods init and destroy and of the methods in the ServletConfig interface.
GenericServlet also implements the log method, declared in the ServletContext
interface.
You may create a generic servlet by inheriting the GenericServlet class and providing
the implementation of the service method.
javax.servlet.http.HttpServlet
Signature: public abstract class HttpServlet extends GenericServlet implements
java.io.Serializable
HttpServlet defines a HTTP protocol specific servlet.
HttpServlet gives a blueprint for Http servlet and makes writing them easier.
HttpServlet extends the GenericServlet and hence inherits the
properties GenericServlet.
Servlet Example by inheriting the GenericServlet class-
Let's see the simple example of servlet by inheriting the GenericServlet class.
import java.io.*;
import javax.servlet.*;
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello generic servlet</b>");
out.print("</body></html>");
}
}
Class HttpServlet
Posted by Rakesh Singh
The HttpServlet class extends the GenericServlet class and implements Serializable
interface. It provides http specific methods such as doGet, doPost, doHead, doTrace
etc. The javax.servlet.http.HttpServlet class is a slightly more advanced base class than
the GenericServlet.
The HttpServlet class reads the HTTP request, and determines if the request is an
HTTP GET, POST, PUT, DELETE, HEAD etc. and calls one the corresponding
method.
Similar to the GenericServlet class this class is also abstract and we extend it make the
SubClass work like a servlet. The SubClass must override one of the following
methods:-
doGet() - for HTTP GET requests
doPost() - for HTTP POST requests
doDelete() - for HTTP DELETE requests
doPut() - for HTTP PUT requests
init()/destroy() - for managing the resources during the life of the servlet
getServletInfo() - this method is used by the servlet to provide information about
itself
service() method of HTTPServlet class is not abstract as was the case in the
GenericServlet class and there is hardly any need to override that method as by default
it contains the capability of deciding the type of the HTTP request it receives and based
on that it calls the specific method to do the needful. For example, if an HTTP GET
request calls the servlet then the service nethod of the HTTPServlet class determines
the request type (it'll find it to be GET) and subsequently calls doGet() method to serve
the request.
To respond to e.g. HTTP GET requests only, you will extend the HttpServlet class, and
override the doGet() method only. Here is an example:
view plainprint?
I would recommend you to use the HttpServlet instead of the GenericServlet whenever
possible. HttpServlet is easier to work with, and has more convenience methods than
GenericServlet.
HttpRequest
Posted by Rakesh Singh
The purpose of the HttpRequest object is to represent the HTTP request a browser
sends to your web application. Thus, anything the browser may send, is accessible via
the HttpRequest.
The HttpRequest object has a lot of methods, so I will just cover the most commonly
used here.
1. Parameters
2. Headers
3. InputStream
4. Session
5. ServletContext
Parameters
The request parameters are parameters that are sent from the browser along with the
request. Request parameters are typically sent as part of the URL (in the "query string"),
or as part of the body of an HTTP request. For instance:
http://www.dineshonjava.com/somePage.html?param1=hello&m2=world
Notice the "query string" part of the URL: ?param1=hello&m2=world This part
contains two parameters with parameter values:
param1=hello
param2=world
You can access these parameters from the HttpRequest object like this:
}
You would use the same code, if the request parameters were sent in the body part of
the HTTP request. If no parameter exists with the given name, null is returned.
In general, if the browser sends an HTTP GET request, the parameters are included in
the query string in the URL. If the browser sends an HTTP POST request, the
parameters are included in the body part of the HTTP request.
Headers
The request headers are name, value pairs sent by the browser along with the HTTP
request. The request headers contain information about e.g. what browser software is
being used, what file types the browser is capable of receiving etc. In short, at lot of
meta data around the HTTP request.
You can access the request headers from the HttpRequest object like this:
The Content-Length header contains the number of bytes sent in the HTTP request
body, in case the browser sends an HTTP POST request. If the browser sends an
HTTP GET request, the Content-Length header is not used, and the above code will
return null.
In general, If no header exists with the name passed to getHeader(), null is returned.
InputStream
If the browser sends an HTTP POST request, request parameters and other potential
data is sent to the server in the HTTP request body. It doesn't have to be request
parameters that is sent in the HTTP request body. It could be pretty much any data, like
a file or a SOAP request (web service request).
To give you access to the request body of an HTTP POST request, you can obtain an
InputStream pointing to the HTTP request body. Here is how it is done:
What you do with the data read from the InputStream is up to you. The servlet engine
does not help you parse or interprete that data. You just get it raw.
Session
It is possible to obtain the session object from the HttpRequest object too.
The session object can hold information about a given user, between requests. So, if
you set an object into the session object during one request, it will be available for you
to read during any subsequent requests within the same session time scope.
Here is how you access the session object from the HttpRequest object:
ServletContext
You can access the ServletContext object from the HttpRequest object too. The
ServletContext contains meta information about the web application. For instance, you
can access context parameters set in the web.xml file, you can forward the request to
other servlets, and you can store application wide parameters in the ServletContext too.
Here is how you access the ServletContext object from the HttpRequest object:
HttpResponse Servlet
Posted by Rakesh Singh
The response object also has the getWriter() method to return a PrintWriter object.
The print() and println() methods of thePrintWriter object write the servlet response
back to the client.
For instance, here is the signature of the HttpServlet.doGet() method:
}
In this text I will look at the HttpResponse object.
The purpose of the HttpResponse object is to represent the HTTP response your web
application sends back to the browser, in response to the HTTP request the browser
send to your web application.
The HttpResponse object has a lot of methods, so I will just cover the most commonly
used here. The rest you can read about in the JavaDoc, if you are interested. The parts
I will cover are:
1. Writing HTML
2. Headers
3. Content-Type
4. Writing Text
5. Content-Length
6. Writing Binary Data
7. Redirecting to a Different URL
8. Writing HTML
To send HTML back to the browser, you have to obtain the a PrintWriter from the
HttpResponse object. Here is how:
Content-Type
The Content-Type header is a response header that tells the browser the type of the
content you are sending back to it. For instance, the content type for HTML is text/html.
Similarly, if what you send back to the browser is plain text, you use the content type
text/plain.
Here is how you set the Content-Type header on the HttpResponse object:
response.setHeader("Content-Type", "text/html");
Writing Text
You can write text back to the browser instead of HTML, like this:
response.setHeader("Content-Type", "text/plain");
Content-Length
The Content-Length header tells the browser how many bytes your servlet is sending
back. If you are sending binary data back you need to set the content length header.
Here is how:
response.setHeader("Content-Length", "31642");
You can search for "mime types" in your favourite search engine to find a list of mime
types (content types), so you can find the mime type for the content you are sending
back.
In order to write binary data back to the browser you cannot use the Writer obtained
from response.getWriter(). Afterall, Writer's are intended for text.
response.sendRedirect("http://www.dineshonjava.com");
Create the HTTP response
After the servlet request code, add the response code:
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
Enumeration keys;
String key;
String myName = "";
keys = request.getParameterNames();
while (keys.hasMoreElements())
{
key = (String) keys.nextElement();
if (key.equalsIgnoreCase("myName")) myName =
request.getParameter(key);
}
System.out.println("Name = ");
if (myName == "") myName = "Hello";
response.setContentType("text/html");
response.setHeader("Pragma", "No-cache");
response.setDateHeader("Expires", 0);
response.setHeader("Cache-Control", "no-cache");
}
}