Advanced Java
Unit 3 Servlet and JSP
3.1 Introduction
3.2 How It differs from CGI
3.3 Types of Servlet
3.4 Life cycle of Servlet
3.5 Execution process of Servlet Application
3.6 Session Tracking
3.7 Cookie class
3.8 Servlet- JDBC
Introduction
In the early days of the Web, most business Web pages were simply forms of advertising
tools and content providers offering customers useful manuals, brochures and catalogues.
In other words, these business-web-pages had static content and were called "Static
WebPages".
Later, the dot-com revolution enabled businesses to provide online services for their
customers; and instead of just viewing inventory, customers could also purchase it. This new
phase of the evolution created many new requirements;
Web sites had to be reliable, available, secure, and, if it was at all possible, fast. At this time,
the content of the web pages could be generated dynamically, and were called "Dynamic
WebPages".
JSP is a server side technology which helps to create a webpage dynamically using java as
the programming language.
JSP is a specification from Sun Microsystems. It is an extension to Servlet API.
Servlet technology is used to create web application (resides at server side and generates
dynamic web page).
What is a Servlet?
1. Servlet is a technology i.e. used to create web application.
2. Servlet is an API that provides many interfaces and classes including
documentations.
3. Servlet is an interface that must be implemented for creating any servlet.
4. Servlet is a class that extends the capabilities of the servers and responds to the
incoming request. It can respond to any type of requests.
5. Servlet is a web component that is deployed on the server to create dynamic web
page.
What is web application?
A web application is an application accessible from the web. A web application is composed
of web components like Servlet, JSP, Filter etc. and other components such as HTML. The
web components typically execute in Web Server and respond to HTTP request.
Contact: [email protected] Call:9763 9763 33, 020-65009763 | 1
www.vertexitservices.com
Advanced Java
Advantages 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, lightweight, cost of communication
between the threads are low. The basic benefits of servlet are as follows:
The advantages of servlets are discussed below.
1. Portability
2. Powerful
3. Efficiency
4. Safety
5. Integration
6. Extensibility
7. Inexpensive
8. Secure
9. Performance
Portability
Servlets are highly portable crosswise operating systems and server implementations
because the servlets are written in java and follow well known standardized APIs. Servlets
are writing once, run anywhere (WORA) program, because we can develop a servlet on
Windows machine running the tomcat server or any other server and later we can deploy
that servlet simply on any other operating system like Unix. Servlets are extremely portable
so we can run in any platform. So we can call servlets are platform independent one.
Servlets are written entirely in java.
Powerful
We can handle several things with the servlets which were difficult or sometimes impossible
to do with CGI. For example the CGI programs can’t talk directly to the web server but the
servlets can directly talk to the web server. Servlets can share data among each other, they
make the database connection pools easy to implement. By using the session tracking
mechanism servlets can maintain the session which helps them to maintain information
from request to request. Servlets can do many things which are difficult to implement in the
CGI programs.
Efficiency
The servlets invocation is highly efficient as compared to CGI programs. The servlet remains
in the server’s memory as a single object instance, when the servlet get loaded in the server.
Contact: [email protected] Call:9763 9763 33, 020-65009763 | 2
www.vertexitservices.com
Advanced Java
The servlets are highly scalable because multiple concurrent requests are handled by
separate threads. That is we can handle N number of threads by using a single servlet class
Safety
As servlets are written in java, servlets inherit the strong type safety of java language. In java
automatic garbage collection mechanism and a lack of pointers protect the servlets from
memory management problems. In servlets we can easily handle the errors due to the
exception handling mechanism. If any exception occurs then it will throw an exception by
using the throw statement.
Integration
Servlets are tightly integrated with the server. Servlet can use the server to translate the file
paths, perform logging, check authorization, and MIME type mapping etc.
Extensibility
The servlet API is designed in such a way that it can be easily extensible. As it stands today,
the servlet API support Http Servlets, but in later date it can be extended for another type of
servlets. 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. So servlets are more extensible and reliable.
Inexpensive
There are number of free web servers available for personal use or for commercial purpose.
Web servers are relatively expensive. So by using the free available web servers you can add
servlet support to it.
Secure
Servlets are server side components, so it inherits the security provided by the web server.
Servlets are also benefited with Java Security Manager.
Performance
Servlets are faster than CGI programs because each scripts in CGI produces a new process
and these processes takes a lot of time for execution. But in case of servlets it creates only
new thread. 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.
Servlet Disadvantage
1. Designing in servlet is difficult and slows down the application.
2. Writing complex business logic makes the application difficult to understand.
3. You need a Java Runtime Environment on the server to run servlets. CGI is a
completely language independent protocol, so you can write CGIs in whatever
languages you have available (including Java if you want to).
Types of Servlets
There are mainly two types of servlets
1. Generic Servlet - Generic servlet is protocol independent servlet. It implements the
Servlet and ServletConfig interface. It may be directly extended by the servlet.
Writing a servlet in in GenericServlet is very easy. It has only init() and destroy()
method of ServletConfig interface in its life cycle. It also implements the log method
of ServletContext interface. They extend javax.servlet.GenericServlet.
2. Http Servlet - HttpServlet is HTTP (Hyper Text Transfer Protocol ) specific servlet. It
provides an abstract class HttpServlet for the developers for extend to create
Contact: [email protected] Call:9763 9763 33, 020-65009763 | 3
www.vertexitservices.com
Advanced Java
their own HTTP specific servlets. They extend javax.servlet.HttpServlet. The sub
class of HttpServlet must overwrite at least one method given below-
a. doGet()
b. doPost()
c. doTrace()
d. doDelete()
e. init()
f. destroy()
g. getServiceInfo()
Servlet Terminology
There are some key points that must be known by the servlet programmer like server,
container, get request, post request etc. Let's first discuss these points before starting the
servlet technology.
The basic terminology used in servlet are given below:
1. HTTP
2. HTTP Request Types
3. Difference between Get and Post method
4. Container
5. Server and Difference between web server and application server
6. Content Type
7. Introduction of XML
8. Deployment
HTTP (Hyper Text Transfer Protocol)
1. Http is the protocol that allows web servers and browsers to exchange data over the
web.
2. It is a request response protocol.
3. Http uses reliable TCP connections by default on TCP port 80.
4. It is stateless means each request is considered as the new request. In other words,
server doesn't recognize the user by default.
Contact: [email protected] Call:9763 9763 33, 020-65009763 | 4
www.vertexitservices.com
Advanced Java
Http Request Methods
Every request has a header that tells the status of the client. There are many request
methods. Get and Post requests are mostly used.
The http request methods are:
1. GET
2. POST
3. HEAD
4. PUT
5. DELETE
6. OPTIONS
7. TRACE
HTTP Description
Request
GET Asks to get the resource at the requested URL.
POST Asks the server to accept the body info attached. It is like GET request with extra info
sent with the request.
HEAD Asks for only the header part of whatever a GET would return. Just like GET but with no
body.
TRACE Asks for the loopback of the request message, for testing or troubleshooting.
PUT Says to put the enclosed info (the body) at the requested URL.
DELETE Says to delete the resource at the requested URL.
OPTIONS Asks for a list of the HTTP methods to which the thing at the request URL can respond
What is the difference between Get and Post?
There are many differences between the Get and Post request. Let's see these differences:
GET POST
1) In case of Get request, only limited amount of In case of post request, large amount of data
data can be sent because data is sent in header. can be sent because data is sent in body.
2) Get request is not secured because data is exposed Post request is secured because data is not
in URL bar. exposed in URL bar.
3) Get request can be bookmarked Post request cannot be bookmarked
4) Get request is idempotent. It means second request Post request is non-idempotent
will be ignored until response of first request is
delivered.
5) Get request is more efficient and used more than Post request is less efficient and used less
Post than get.
Contact: [email protected] Call:9763 9763 33, 020-65009763 | 5
www.vertexitservices.com
Advanced Java
Anatomy of Get Request
As we know that data is sent in request header in case of get request. It is the default
request type. Let's see what informations are sent to the
server.
Anatomy of Post Request
As we know, in case of post request original data is sent in message body. Let's see how
informations are passed to the server in case of post
request.
Container
It provides runtime environment for JavaEE (j2ee) applications.It performs many operations
that are given below:
1. Life Cycle Management
2. Multithreaded support
3. Object Pooling
4. Security etc.
5. Server
It is a running program or software that provides services.There are two types of servers:
1. Web Server
2. Application Server
Contact: [email protected] Call:9763 9763 33, 020-65009763 | 6
www.vertexitservices.com
Advanced Java
Web Server
Web server contains only web or servlet container. It can be used for servlet, jsp, struts, jsf
etc. It can't be used for EJB.
Example of Web Servers are: Apache Tomcat and Resin.
Application Server
Application server contains Web and EJB containers. It can be used for servlet, jsp, struts, jsf,
ejb etc.
Example of Application Servers are:
1. JBoss Open-source server from JBoss community.
2. Glassfish provided by Sun Microsystem. Now acquired by Oracle.
3. Weblogic provided by Oracle. It more secured.
4. Websphere provided by IBM.
Content Type
Content Type is also known as MIME (Multipurpose internet Mail Extension) Type. It is
a HTTP header that provides the description about what are you sending to the browser.
There are many content types:
1. text/html
2. text/plain
3. application/msword
4. application/vnd.ms-excel
5. application/jar
6. application/pdf
7. application/octet-stream
8. application/x-zip
9. images/jpeg
10. video/quicktime etc.
Servlet API
1. The javax.servlet and javax.servlet.http packages represent interfaces and classes for
servlet api.
2. The javax.servlet package contains many interfaces and classes that are used by the
servlet or web container. These are not specific to any protocol.
3. The javax.servlet.http package contains interfaces and classes that are responsible
for http requests only.
Let's see what are the interfaces of javax.servlet package.
Interfaces in javax.servlet package
There are many interfaces in javax.servlet package. They are as follows:
1. Servlet
2. ServletRequest
3. ServletResponse
4. RequestDispatcher
5. ServletConfig
6. ServletContext
7. SingleThreadModel
8. Filter
9. FilterConfig
10. FilterChain
11. ServletRequestListener
Contact:
[email protected] Call:9763 9763 33, 020-65009763 | 7
www.vertexitservices.com
Advanced Java
12. ServletRequestAttributeListener
13. ServletContextListener
14. ServletContextAttributeListener
There are many classes in javax.servlet package. They are as follows:
1. GenericServlet
2. ServletInputStream
3. ServletOutputStream
4. ServletRequestWrapper
5. ServletResponseWrapper
6. ServletRequestEvent
7. ServletContextEvent
8. ServletRequestAttributeEvent
9. ServletContextAttributeEvent
10. ServletException
11. UnavailableException
Interfaces in javax.servlet.http package
There are many interfaces in javax.servlet.http package. They are as follows:
1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
4. HttpSessionListener
5. HttpSessionAttributeListener
6. HttpSessionBindingListener
7. HttpSessionActivationListener
8. HttpSessionContext (deprecated now)
Classes in javax.servlet.http package
There are many classes in javax.servlet.http package. They are as follows:
HttpServlet
1. Cookie
2. HttpServletRequestWrapper
3. HttpServletResponseWrapper
4. HttpSessionEvent
5. HttpSessionBindingEvent
6. HttpUtils (deprecated now)
Servlet Interface
1. Servlet interface provides common behaviour to all the servlets.
2. 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.
Methods of Servlet interface
There are 5 methods in Servlet interface. The init, service and destroy are the life cycle
methods of servlet. These are invoked by the web container.
Method Description
public void init(ServletConfig config) initializes the servlet. It is the life cycle method of
servlet and invoked by the web container only once.
public void service(ServletRequest provides response for the incoming request. It is
request,ServletResponse response) invoked at each request by the web container.
public void destroy() is invoked only once and indicates that servlet is being
destroyed.
Contact: [email protected] Call:9763 9763 33, 020-65009763 | 8
www.vertexitservices.com
Advanced Java
public ServletConfig getServletConfig() returns the object of ServletConfig.
public String getServletInfo() returns information about servlet such as writer,
copyright, version etc.
GenericServlet class
1. GenericServlet class implements Servlet, ServletConfig andSerializable interfaces. It
provides the implementaion of all the methods of these interfaces except the
service method.
2. GenericServlet class can handle any type of request so it is protocol-independent.
3. You may create a generic servlet by inheriting the GenericServlet class and providing
the implementation of the service method.
Methods of GenericServlet class
There are many methods in GenericServlet class. They are as follows:
1. public void init(ServletConfig config) is used to initialize the servlet.
2. public abstract void service(ServletRequest request, ServletResponse
response) provides service for the incoming request. It is invoked at each time when
user requests for a servlet.
3. public void destroy() is invoked only once throughout the life cycle 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.
6. public void init() it is a convenient method for the servlet programmers, now there is
no need to call super.init(config)
7. public ServletContext getServletContext() returns the object of ServletContext.
8. public String getInitParameter(String name) returns the parameter value for the
given parameter name.
9. public Enumeration getInitParameterNames() returns all the parameters defined in
the web.xml file.
10. public String getServletName() returns the name of the servlet object.
11. public void log(String msg) writes the given message in the servlet log file.
12. public void log(String msg,Throwable t) writes the explanatory message in the
servlet log file and a stack trace.
HttpServlet class
The HttpServlet class extends the GenericServlet class and implements Serializable interface.
It provides http specific methods such as doGet, doPost, doHead, doTrace etc.
Methods of HttpServlet class
There are many methods in HttpServlet class. They are as follows:
1. public void service(ServletRequest req,ServletResponse res) dispatches the request
to the protected service method by converting the request and response object into
http type.
2. protected void service(HttpServletRequest req, HttpServletResponse res) receives
the request from the service method, and dispatches the request to the doXXX()
method depending on the incoming http request type.
3. protected void doGet(HttpServletRequest req, HttpServletResponse res) handles the
GET request. It is invoked by the web container.
4. protected void doPost(HttpServletRequest req, HttpServletResponse res) handles
the POST request. It is invoked by the web container.
Contact: [email protected] Call:9763 9763 33, 020-65009763 | 9
www.vertexitservices.com
Advanced Java
5. protected void doHead(HttpServletRequest req, HttpServletResponse res) handles
the HEAD request. It is invoked by the web container.
6. protected void doOptions(HttpServletRequest req, HttpServletResponse res) handles
the OPTIONS request. It is invoked by the web container.
7. protected void doPut(HttpServletRequest req, HttpServletResponse res) handles the
PUT request. It is invoked by the web container.
8. protected void doTrace(HttpServletRequest req, HttpServletResponse res) handles
the TRACE request. It is invoked by the web container.
9. protected void doDelete(HttpServletRequest req, HttpServletResponse res) handles
the DELETE request. It is invoked by the web container.
10. protected long getLastModified(HttpServletRequest req) returns the time when
HttpServletRequest was last modified since midnight January 1, 1970 GMT.
Contact: [email protected] Call:9763 9763 33, 020-65009763 | 10
www.vertexitservices.com