1 Servlets-2021
1 Servlets-2021
Programming
SubjectCode: 18MCA41 I.A. Marks : 40
Hours/Week : 3 ExamHours: 3
TotalHours : 45 ExamMarks: 60
Model 1:Servlets: 9Hours
Servlet Structure, Servlet packaging, HTML building utilities, Lifecycle, Single
Thread model interface,
Handling Client Request: Form Data, Handling Client Request: HTTP Request
Headers. Generating server Response: HTTP Status codes, Generating server
Response: HTTP Response Headers, Handling Cookies, Session Tracking.
Overview of JSP Technology, Need of JSP, Benefits of JSP, Advantages of JSP,
Basic syntax,
Creating Packages, Interfaces, JAR files and Annotations. The core java API
package, New java.Lang Subpackage, Built-in Annotations. Working with Java
Beans. Intro spection, Customizers, creating java bean, manifestfile, Bean
Jarfile, new bean, adding controls, Bean properties, Simple properties, Design
Pattern events, creating bound properties, Bean Methods, Bean an Icon,Bean
info class, Persistence ,Java Beans API.
Model 4:JDBC: 9Hours
Talking to Database, Immediate Solutions, Essential JDBC program, using
prepared Statemen tObject, Interactive SQL tool. JDBC In Action Resultsets,
Batch updates, Mapping, Basic JDBC data types, Advanced JDBC data types,
Immediate solutions. Interducation to EJB: The Problem domain, Break up
responsibilities, Code Smart nothard, the Enterprise java bean specification.
Components Types.
GRNICA 6
Servlets
Servlet: Introduction to Web
Web consists of billions of clients and server connected through wires
and wireless networks. The web clients make requests to web server. The web
server receives the request, finds the resources and return the response to the
client.
When a server answers a request, it usually sends some type of content
to the client. The client uses web browser to send request to the server. The
server often sends response to the browser with a set of instructions written in
HTML( HyperText Markup Language ). All browsers know how to display
HTML page to the client.
Web Application
A website is a collection of static files(webpages) such as HTML pages,
images, graphics etc. A Web application is a web site with dynamic
functionality on the server. Google, Facebook, Twitter are examples of web
applications.
HTTP (Hypertext Transfer Protocol)
•HTTP is a protocol that clients and servers use on the web to communicate.
•It is similar to other internet protocols such as SMTP(Simple Mail Transfer
Protocol) and FTP(File Transfer Protocol) but there is one fundamental
difference.
•HTTP is a stateless protocol i.e HTTP supports only one request per
connection. This means that with HTTP the clients connect to the server to send
one request and then disconnects. This mechanism allows more users to connect
to a given server over a period of time.
•The client sends an HTTP request and the server answers with an HTML page
to the client, using HTTP.
Servl
etsside
Servlet technology is used to create web application (resides at server
and generates dynamic web page).
GRNICA 12
GRNICA 13
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, we 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.
several advantages in comparison with the CGI.
GRNICA 16
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 many
benefits over the Processes such as they share a common memory area,
lightweight, cost of communication between the threads are low.
GRNICA 17
The advantages of Servlet are as follows:
•Better performance: because it creates a thread for each request, not
process.
•Portability: because it uses Java language.
•Robust: JVM manages Servlets, so we don't need to worry about the
memory leak, garbage collection, etc.
•Secure: because it uses java language.
GRNICA 18
Servlets Architecture
GRNICA 19
What is a Servlet?
Servlet can be described in many ways, depending on the context.
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 extend the capabilities of the servers and respond 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.
GRNICA 20
6. Servlets are small programs that execute on the server side of a
Web connection.
7. Servlets are server side components that provides a powerful
mechanism for developing server web applications for server side.
8. Just as applets dynamically extend the functionality of a Web
browser, servlets dynamically extend the functionality of a Web
server.
9. Using servlets web developers can create fast and efficient server side
applications and can run it on any servlet enabled web server.
10. Servlet runs entirely inside the Java Virtual Machine.
11. Since the servlet runs on server side so it does not depend on
browser compatibility.
GRNICA 21
Background
• In order to understand the advantages of servlets, you must have a
basic understanding of how Web browsers and servers cooperate to
provide content to a user.
Client
Server
The HTTP header in response indicate the
type of the content & MIME is used for
this purpose.
GRNICA 22
• But the content of the dynamic web pages need to be generated
dynamically.
• In the early days of the Web, a server could dynamically construct a
page by creating a separate process to handle each client request.
• The process would open connections to one or more databases in
order to obtain the necessary information.
• It communicated with the Web server via an interface known as the
Common Gateway Interface (CGI).
• CGI allowed the separate process to read data from the HTTP
request and write data to the HTTP response.
• However, CGI suffered serious performance problems. It was
expensive in terms of processor and memory resources to create a
separate process for each client request.
GRNICA 23
GRNICA 24
GRNICA 25
The Life Cycle of a Servlet
• init( ), service( ), and destroy( ) are the three methods which are central to the life cycle of a servlet &
one more doGet( ) or doPost( )
• They are implemented by every servlet and are invoked at specific times by the server.
• Let us consider a user scenario to understand when these methods are called.
• First, user enters URL, browser then generates an HTTP request for this URL, & this request is then sent
to the appropriate server.
• second, this HTTP request is received by web server, web server maps this request to a particular servlet.
The servlet is dynamically retrieved & loaded into the address space of the server.
• Third, server invokes init( ) method of the servlet. This method is invoked only when the servlet is first
loaded into memory. It is possible to pass initialization parameters to the servlet so it may configure itself.
• Fourth, the server invokes the service( ) method of the servlet. This method is called to process the
HTTP request. It may also formulate an HTTP response for the client. The service( ) method is called for
each HTTP request.
• Finally, the server may decide to unload the servlet from its memory. The server calls the destroy( )
method to any resources such as file handles that are allocated for the servlet.
GRNICA 26
GRNICA 26
Do Get( ) or doPost( )
GRNICA 27
A Simple Servlet
• The basic steps to be followed:
1.Create and compile the servlet source code.
2.Start Tomcat.
3.Start a Web browser and request the servlet.
GRNICA 28
A Simple Servlet Code This The
package contains the class
GenericServlet classes and interfaces
provides functionality
required
that to builditservlets.
makes easy to handle requests and
import java.io.*; responses.
import javax.servlet.*;
GRNICA 29
Servlet Packaging
• In a production environment, multiple programmers can be
developing servlets for the same server.
• So, placing all the servlets in the same directory results in a
massive, hard-to-manage collection of classes and risks name
conflicts when two developers choose the same name for a servlet
or a utility class.
• Web applications helps to solve with this problem by dividing
things up into separate directories, each with its own set of
servlets, utility classes, JSP pages, and HTML files.
• Sometimes even a single Web application can be large, we still
need the standard Java solution for avoiding name conflicts:
packages.
The Servlet API (Servlet Packaging)
•javax.servlet
•javax.servlet.http are the two packages that
contains the classes required to build servlet.
• These packages are not part of Java core packages, they are standard
extensions provided by Tomcat.
• The current servlet specification is version 2.4.
• The Servlet API is supported by most Web servers, such as those
from Sun, Microsoft, and others.
GRNICA 32
B. The ServletConfig Interface
•All servlets must implement the Servlet interface.
•It allows a servlet to obtain configuration data when it is loaded.
• The methods declared by this interface are summarized here:
33
C. The ServletContext Interface
• ServletContext is a interface which helps us to communicate with
the servlet container.
• It enables servlets to obtain information about their environment.
• Each servlet will have its own ServletConfig.
• The ServetContext is created by the container when the web
application is deployed and after that only the context is available to
each servlet in the web application.
GRNICA 34
• Several of its methods are summarized in table below.
GRNICA 35
D. The ServletRequest Interface
• It enables a servlet to obtain information about a client request.
• Several of its methods are summarized in table below.
GRNICA 36
E. The ServletResponse Interface
• It enables a servlet to formulate a response for a client.
• Several of its methods are summarized in table below.
GRNICA 37
• The following table summarizes the core classes that are provided
in the javax.servlet package.
GRNICA 38
A. The GenericServlet Class
• The GenericServlet class provides implementations of the basic
life cycle methods for a servlet.
• GenericServlet implements the Servlet and ServletConfig
interfaces.
• In addition, a method to append a string to the server log file is
available. The signatures of this method are shown here:
void log(String s)
void log(String s, Throwable e)
GRNICA 40
C. The ServletOutputStream Class
• The ServletOutputStream class extends OutputStream.
• It is implemented by the server and provides an output stream that a
servlet developer can use to write data to a client response.
• A default constructor is defined. It also defines the print( ) and
println( ) methods, which output data to the stream.
GRNICA 42
2. The javax.servlet.http Package
• The javax.servlet.http package contains a number of interfaces and
classes that are commonly used by servlet developers.
GRNICA 43
The HttpServletRequest Interface
• The HttpServletRequest interface is implemented by the server. It
enables a servlet to obtain information about a client request.
• Several of its methods are shown in Table below.
GRNICA 44
GRNICA 45
GRNICA 46
The HttpServletResponse Interface
• The HttpServletResponse interface is implemented by the server. It
enables a servlet to formulate an HTTP response to a client.
• Several constants are defined. These correspond to the different
status codes that can be assigned to an HTTP response.
• For example, SC_OK indicates that the HTTP request succeeded
and SC_NOT_FOUND indicates that the requested resource is not
available.
GRNICA 47
GRNICA 48
GRNICA 49
The HttpSession Interface
• The HttpSession interface is implemented by the server. It enables a
servlet to read and write the state information that is associated with
an HTTP session.
GRNICA 50
GRNICA 51
Simple HTML-Building Utilities
<!DOCTYPE.......>
<HTML>
<HEAD><TITLE>........</TITLE></HEAD>
<BODY>.......</BODY>
</HTML>
• When using servlets to build the HTML, we might be tempted to omit the
DOCTYPE line, virtually all major browsers ignore it even though the HTML
specifications require it.
• They let us submit a URL, then they retrieve the page, check the
syntax against the formal HTML specification, and report any
errors to us.
package coreservlets;
import javax.servlet.*;
import javax.servlet.http.*;
First time when a request comes to a Web server for a Servlet, the Web
container loads the Servlet, creates a Servlet object, executes the
callback service() method.
• This means that if a new request comes in while a previous
request is still executing, multiple threads can concurrently be
accessing the same servlet object.
For the other visitor, a thread is created in the same process
(in the same service() method). To be more clear, if 100 requests
come concurrently for the same servlet, 100 threads are created within
the same process (or one process). We know each thread maintains its
own set of instance variables.
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 we can parse and use for our processing. Servlet
handles this type of requests using doPost()method
Reading Form Data using Servlet
Servlets handles form data parsing automatically using the following
methods depending on the situation −
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Reading Three Request Parameters";
out.println("<HTML>\n" +
"<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=\"CENTER\">" + title + "</H1>\n" +
"<UL>\n" +
" <LI><B>param1</B>: "
+ request.getParameter("param1") + "\n" +
" <LI><B>param2</B>: "
+ request.getParameter("param2") + "\n" +
" <LI><B>param3</B>: "
+ request.getParameter("param3") + "\n" +
"</UL>\n" +
"</BODY></HTML>");
}
}
HANDLING THE CLIENT REQUEST:
HTTP REQUEST HEADERS
• Form data results directly from user input and is sent as part of the
URL for GET requests and on a separate line for POST requests.
• Request headers, on the other hand, are indirectly set by the browser
and are sent immediately following the initial GET or POST request
line.
HTTP 1.1 Request Headers
• Accept : This header specifies the MIME types that the browser
or other clients can handle. A servlet that can return a resource in
more than one format can examine the Accept header to decide
which format to use.
• Accept-Charset : This header indicates the character sets (e.g.,
ISO-8859-1) the browser can use.
• Accept-Encoding : This header designates the types of
encodings that the client knows how to handle. If the server
receives this header, it is free to encode the page by using one of
the formats specified.
• Accept-Language : This header specifies the client’s preferred
languages in case the servlet can produce results in more than one
language.
• Authorization : 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.
• Content-Length : This header is applicable only to POST requests
and gives the size of the POST data in bytes.
• Cookie : This header returns cookies to servers that previously sent
response.setStatus, response.sendRedirect, or
response.sendError.
HTTP 1.1 Status Codes
• 300–399 : Values in the 300s are used for files that have moved
and usually include a Location header indicating the new address.
Constructor Description
Cookie() constructs a cookie.
Cookie(String name, constructs a cookie with a specified name and
String value) value.
GRNICA 88
Servlet Cookies Methods:
Following is the list of useful methods which you can use while
manipulating cookies in servlet.
GRNICA 91
How to get Cookies?
Let's see the simple code to get all the cookies.
Cookie ck[]=request.getCookies();
for(int i=0; i<ck.length; i++)
{
out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());
//printing name and value of cookie
}
GRNICA 92
Benefits of Cookies
• Identifying a user during an e-commerce session : HTTP cookies
are used by web servers to differentiate users and to maintain data
related to the user during navigation, possibly across multiple visits.
GRNICA 96
Placing the Cookie in the Response Headers
• To send the cookie, insert it into a Set-Cookie HTTP response
header by means of the addCookie method of HttpServletResponse.
• The method is called addCookie, not setCookie, because any
previously specified Set-Cookie headers are left alone and a new
header is set.
• The response headers must be set before any document content is
sent to the client.
• Here is an example:
Cookie userCookie = new Cookie("user", "uid1234");
userCookie.setMaxAge(60*60*24*365);//Store cookie for
1 year
response.addCookie(userCookie);
GRNICA 97
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:
Each request is
independent of the
GRNICA 98
previous one.
However, in some applications, it is necessary to save state
information so that information can be collected from several
interactions between a browser and a server. Sessions provide
such a mechanism.
• A session can be created via the getSession( ) method of
HttpServletRequest.
• An HttpSession object is returned. This object can store a set of
bindings that associate names with objects.
• The setAttribute( ), getAttribute( ), getAttributeNames( ), and
removeAttribute( ) methods of HttpSession manage these
bindings.
GRNICA 99
Snooping the server
GRNICA 106
In normal Java Application we have to invoke Java Interpter, it
will start through main.?
Servlets have live cycle
Client Request->Container->Invokes the HTTP method automatically
GRNICA 107