MODULE- 5
JAVA Servelet
Web Terminology
Servlet Description
Terminology
Website: static vs It is a collection of related web pages that may contain text, images, audio
dynamic and video.
HTTP It is the data communication protocol used to establish communication
between client and server.
HTTP Requests It is the request send by the computer to a web server that contains all
sorts of potentially interesting information.
Get vs Post It gives the difference between GET and POST request.
Container It is used in java for dynamically generating the web pages on the server
side.
Server: Web vs It is used to manage the network resources and for running the program or
Application software that provides services.
Content Type It is HTTP header that provides the description about what are you sending
to the browser.
A Java servlet is a Java software component that extends the capabilities of a server.
Although servlets can respond to any types of requests, they most commonly
implement web containers for hosting web applications on web servers and thus qualify
as a server-side servlet web API. Such web servlets are the Java counterpart to
other dynamic web contenttechnologies such as PHP and ASP.NET.
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.
SERVELET ARCHITECTURE
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
SERVELET LIFE CYCLE
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.
The init() Method
The init method is called only once. It is called only when the servlet is created, and not
called for any user requests afterwards. So, it is used for one-time initializations, just as
with the init method of applets.
The servlet is normally created when a user first invokes a URL
corresponding to the servlet, but you can also specify that the servlet be
loaded when the server is first started.
The service() Method
The service() method is the main method to perform the actual task. The servlet
container (i.e. web server) calls the service() method to handle requests coming from
the client( browsers) and to write the formatted response back to the client.
Each time the server receives a request for a servlet, the server spawns a
new thread and calls service. The service() method checks the HTTP
request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut,
doDelete, etc. methods as appropriate.
The doGet() Method
A GET request results from a normal request for a URL or from an HTML
form that has no METHOD specified and it should be handled by doGet()
method.
The doPost() Method
A POST request results from an HTML form that specifically lists POST as the METHOD
and it should be handled by doPost() method.
The destroy() Method
The destroy() method is called only once at the end of the life cycle of a servlet. This
method gives your servlet a chance to close database connections, halt background
threads, write cookie lists or hit counts to disk, and perform other such cleanup
activities.
After the destroy() method is called, the servlet object is marked for garbage collection.
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.
Get vs. 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 In case of post request, large amount
amount of data can be sent because data of data can be sent because data is
is sent in header. sent in body.
2) Get request is not secured because data Post request is secured because data
is exposed in URL bar. is not exposed in URL bar.
3) Get request can be bookmarked. Post request cannot be bookmarked.
4) Get request is idempotent . It means Post request is non-idempotent.
second request will be ignored until response
of first request is delivered
5) Get request is more efficient and used Post request is less efficient and used
more than Post. less than get.
HTTP Requests
The request sent by the computer to a web server, contains all sorts of potentially interesting information;
it is known as HTTP requests.
The HTTP client sends the request to the server in the form of request message which includes following
information:
o The Request-line
o The analysis of source IP address, proxy and port
o The analysis of destination IP address, protocol, port and host
o The Requested URI (Uniform Resource Identifier)
o The Request method and Content
o The User-Agent header
o The Connection control header
o The Cache control header
The HTTP request method indicates the method to be performed on the resource identified by
theRequested URI (Uniform Resource Identifier). This method is case-sensitive and should be used in
uppercase.
The HTTP request methods are:
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
Some Important Methods of HttpServletResponse
Methods Description
void addCookie(Cookie cookie) adds the specified cookie to the response.
void sendRedirect(String Sends a temporary redirect response to the client using the
location) specified redirect location URL and clears the buffer
int getStatus() gets the current status code of this response
String getHeader(String name) gets the value of the response header with the given name.
void setHeader(String name, sets a response header with the given name and value
String value)
void setStatus(int sc) sets the status code for this response
void sendError(int sc, String sends an error response to the client using the specified
msg) status and clears the buffer
SESSION TRACKING
Session simply means a particular interval of time.
Session Tracking is a way to maintain state (data) of an user. It is also known as session
management in servlet.
Http protocol is a stateless so we need to maintain state using session tracking techniques. Each time user
requests to the server, server treats the request as the new request. So we need to maintain the state of
an user to recognize to particular user.
HTTP is stateless that means each request is considered as the new request. It is shown in the figure given
below:
Why use Session Tracking?
To recognize the user It is used to recognize the particular user.
Session Tracking Techniques
There are four techniques used in Session tracking:
1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession
Cookies for Session Management
Cookies are small pieces of information that are sent in response from the web server to the
client. Cookies are the simplest technique used for storing client state.
Cookies are stored on client's computer. They have a lifespan and are destroyed by the
client browser at the end of that lifespan.
Using Cookies for storing client state has one shortcoming though, if the client has turned of
COokie saving settings in his browser then, client state can never be saved because the
browser will not allow the application to store cookies.
Cookies API
Cookies are created using Cookie class present in Servlet API. Cookies are added
to responseobject using the addCookie() method. This method sends cookie information
over the HTTP response stream. getCookies() method is used to access the cookies that are
added to response object.
SERVELET SECURITY
JavaServer Pages and servlets make several mechanisms available to Web developers
to secure applications. Resources are protected declaratively by identifying them in the
application deployment descriptor and assigning a role to them.
Several levels of authentication are available, ranging from basic authentication using
identifiers and passwords to sophisticated authentication using certificates.
Role Based Authentication
The authentication mechanism in the servlet specification uses a technique called role-
based security. The idea is that rather than restricting resources at the user level, you
create roles and restrict the resources by role.
Form Based Authentication
When you use the FORM authentication method, you must supply a login form to prompt
the user for a username and password.
Programmatic Security in a Servlet/JSP
The HttpServletRequest object provides the following methods, which can be used to
mine security information at runtime −
S.No. Method & Description
String getAuthType()
1
The getAuthType() method returns a String object that represents the name of the
authentication scheme used to protect the Servlet.
boolean isUserInRole(java.lang.String role)
2 The isUserInRole() method returns a boolean value: true if the user is in the given role
or false if they are not.
String getProtocol()
The getProtocol() method returns a String object representing the protocol that was
3
used to send the request. This value can be checked to determine if a secure protocol
was used.
boolean isSecure()
The isSecure() method returns a boolean value representing if the request was made
4
using HTTPS. A value of true means it was and the connection is secure. A value of false
means the request was not.
Principle getUserPrinciple()
5 The getUserPrinciple() method returns a java.security.Principle object that contains
the name of the current authenticated user.