1. Following are web server
software.
Apache HTTP Server
Microsoft Internet
Information Services (IIS)
Apache Tomcat
Nginx
Oracle iPlanet Web Server
Lighttpd
Mobile Web Server
Mongoose (web server)
Jetty
Wamp Server
Boa web server
CERN httpd
Gunicorn
Kloxo-MR
Roxen
AOLserver
Tornado (web
server)
Adobe JRun
Hiawatha (web
server)
enhydra
WEBrick
2. Web application
Web application servers are designed specifically
to extend web servers to support dynamic
content.
The application server software “hooks in” to
the web server software and automatically
captures any user requests for dynamic content.
The web server still sends out static web pages
and graphic files–Just like before.
But now, the application server can create
dynamic content by mixing data with templates,
running programs, or by accessing databases.
5. WEB AND APPLICATION SERVER AND WEB
CONTAINER
You need a web server like Apache HTTP if you are
serving static web pages.
If you have a Java application with just JSP and
Servlet to generate dynamic content then you need web
containers like Tomcat or Jetty.
While, if you have Java EE application using EJB,
distributed transaction, messaging and other fancy
features than you need a application server like JBoss,
WebSphere or Oracle's WebLogic.
Web container is a part of Web Server and the Web
8. HTTP Request:
HTTP Request means transferring a request
form the client side to the server.
It contains different types of HTTP Request
Methods, which are used to indicate the type
of the request.
It has URI which locate the destination.
It also has Protocol Version (Example:
HTTP/1.1)
Then comes the Request Header, which
contains information regarding the client
environment like, Accept-Charset, Accept-
Encoding, Authorization,etc.
Then there is a Message Body section, which
contains actual information regarding the
9. HTTP Response:
HTTP Response means transferring a
response of the client’s request by the web
server.
First it contains the protocol name, its
version, status code of the request, and a
brief description of the status code.
Then it contains Response Header, which
contain the information of the server side
environment.
After that it has, Message Body, which
contain the actual response for the client.
13. Applet vs Servlet
Applet Servlet
Applet is client side application Servlet is Server side application
runs within a Web browser on the
client machine
servlet runs on the Web server
applet can use the user interface
classes like AWT(Abstract window
Toolkit) or Swing
servlet does not have a user interface
Applet is a browser Servlet is server
init()-Where it can initialise itself
start()- It can start running
stop()-stop running
destroy()-Cleanup process happens
init()
service()
destroy()
doGet(), doPost()
14. Servlet Basic
Servlet technology is used to create web
application (resides at server side and generates
dynamic web page).
Servlets are protocol- and platform-independent
server side components, written in Java, which
dynamically extend Java-enabled servers.
Servlet technology is robust and scalable because
of java language.
Before Servlet, CGI (Common Gateway Interface)
scripting language was popular as a server-side
programming language. But there was many
disadvantages of this technology.
15. There are many interfaces and classes in
the servlet API such as
Servlet,
GenericServlet,
HttpServlet,
ServletRequest,
ServletResponse etc.
16. 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.
19. 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.
20. CGI(Commmon Gateway Interface)
CGI technology enables the web server to call an
external program and pass HTTP request information to
the external program to process the request.
For each request, it starts a new process.
21. 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.
22. 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, lightweight, cost of
communication between the threads are low.
23. The basic benefits of servlet are as follows:
better performance: because it creates a
thread for each request not process.
Portability: because it uses java language.
Robust: Servlets are managed by JVM so we
don't need to worry about memory leak,
garbage collection etc.
Secure: because it uses java language..
24. A Servlet's Job
Read the explicit data sent by the client
Read the implicit HTTP request data sent by the
browser
Generate the results
Send the explicit data (i.e., the document) to the
client
Send the implicit HTTP response data
26. Servlet Terminology
HTTP
HTTP Request Types
Difference between Get and Post method
Container
Server and Difference between web server and
application server
Content Type
Introduction of XML
Deployment
27. 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.
Http uses reliable TCP connections bydefault on
TCP port 80.
30. Container
It provides runtime environment for JavaEE (j2ee)
applications.
It performs many operations that are given below:
Life Cycle Management
Multithreaded support
Object Pooling
Security etc.
31. Server
It is a running program or software that provides
services.
There are two types of servers:
1. Web Server
2. Application Server
32. 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
33. 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:
JBoss Open-source server from JBoss community.
Glassfish provided by Sun Microsystem. Now acquired by
Oracle.
Weblogic provided by Oracle. It more secured.
Websphere provided by IBM.
34. 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:
text/html
text/plain
application/msword
application/vnd.ms-excel
application/jar
application/pdf
application/octet-stream
application/x-zip
images/jpeg
video/quicktime etc.
35. Servlet API
The javax.servlet and javax.servlet.http
packages represent interfaces and classes
for servlet api.
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.
The javax.servlet.http package contains
interfaces and classes that are responsible
for http requests only.
40. URI (uniform resource identifier) identifies a
resource (text document, image file, etc)
URL (uniform resource locator) is a subset of
the URIs that include a network location
URN (uniform resource name) is a subset of
URIs that include a name within a given space,
but no location
42. How to Create Servlet?
ccording to servlet API we have three ways to creating
a servlet class.
By implementing servlet interface
By extending GenericServlet class
By extending HttpServlet class
43. Directory Structure of Servlet
Application
According to directory structure
An application contain root folder with any name.
Under root folder a sub folder is required with a name
WEB-INF.
Under WEB-INF two sub folder are required classes
and lib.
45. The Deployment Descriptor: web.xml
Java web applications use a deployment descriptor file to
determine how URLs map to servlets, which URLs
require authentication, and other information.
This file is named web.xml, and resides in the app's
WAR under the WEB-INF/ directory.
web.xml is part of the servlet standard for web
applications.
A web application's deployment descriptor describes the
classes, resources and configuration of the application
and how the web server uses them to serve web
requests.
When the web server receives a request for the
application, it uses the deployment descriptor to map
the URL of the request to the code that ought to
handle the request.
46. Web.xml in Servlet
We can not change the directory or extension
name of this web.xml because it is standard name
to recognized by container at run-time.
47. Java PrintWriter class
Java PrintWriter class is the implementation of Writer
class. It is used to print the formatted
representation of objects to the text-output
stream.
The servlet binded with the url-pattern is called.
The method being called depends on the kind of
request (doGet, doPost, doPut).
The method normally receives the request and
response objects, we then call the .getWriter()
method for the response obj that gets us the
stream on which we can write our output.
response.getWriter() returns a PrintWriter object
that can send character text to the client.
48. Servlet Interface
Servlet interface provides common behaviour to
all the servlets.
Servlet interface needs to be implemented for
creating any servlet.
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.
51. GenericServlet class
The GenericServlet class implements the Servlet
and ServletConfig interfaces.
Since service () method is declared as an
abstract method in GenericServlet class, it is an
abstract class.
The class extending this class must implement the
service () method.
GenericServlet class can handle any type of
request so it is protocol-independent.
55. 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.
57. Difference between HttpServlet and GenericServlet
both these Classes are Abstract Classes.
GenericServlet is a super class of HttpServlet class.
The main difference is that, HttpServlet is a protocol
dependent whereas GenericServlet is protocol
independent. So GenericServlet can handle all types of
protocols, but HttpServlet handle only HTTP specific
protocols.
GenericServlet belongs to javax.servlet package.
HttpServlet belongs to javax.servlet.http package
GenericServlet is an abstract class which extends Object
and implements Servlet, ServletConfig and
java.io.Serializable interfaces.
HttpServlet is an abstract class which extends
GenericServlet and implements java.io.Serializable
58. GenericServlet supports only service() method does
not contain doGet() and doPost() methods.
HttpServlet support also doGet(), doPost(), doHead()
methods (HTTP 1.0) plus doPut(), doOptions(),
doDelete(), doTrace() methods (HTTP 1.1).
59. Servlets - Life Cycle
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.
60. The init() method :
This method is automatically called whenever a
servlet is initialized.
The developer does not explicitly call the init() method,
instead, it is automatically called the first time the
servlet is called through a URL request.
Only one instance of each servlet is created and used,
and each folowing request creates a new thread
that handles it.
61. The service() method :
The service() method is the main method to perform the
actual task.
This is the main method of handling the requests to
the server.
This method determines the type of the request (POST,
GET, etc) and acts accordingly, by calling the specified
methods like doPost() and doGet().
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
62. The destroy() method :
The destroy() method is called only once at the end of
the life cycle of a servlet.
The destroy method is working similarly to init(), but
trying to achieve the opposite result.
It is not a method that is explicitly called by the
developer.
Instead, when the server (servlet container) decides
that the servlet is no longer in use, and its resources
should be collected and used somewhere else, the
destroy() method is automatically called.
In that case we use destroy() to close connections,
free resources and generally finalize whatever needs
to be finalized for a smooth shutdown of the servlet
and no memory leaks.
66. 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.
67. 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
69. War File
A war (web archive) File contains files of a web
project. It may have servlet, xml, jsp, image, html,
css, js etc. files.
web archive (war) file contains all the contents of a
web application.
It reduces the time duration for transferring file.
Advantage of war file
saves time: The war file combines all the files into a
single unit. So it takes less time while transferring file
from client to server.
70. How to create war file?
To create war file, you need to use jar tool of JDK. You
need to use -c switch of jar, to create the war file.
Go inside the project directory of your project (outside
the WEB-INF), then write the following command:
jar -cvf projectname.war *
Here,
-c is used to create file,
-v to generate the verbose output and
-f to specify the archive file name.
The * (asterisk) symbol signifies that all the files of this
directory (including sub directory).
71. How to deploy the war file?
There are two ways to deploy the war file.
By server console panel
By manually having the war file in specific folder of
server.
If you want to deploy the war file in apache tomcat
server manually, go to the webapps directory of
apache tomcat and paste the war file here.
Now, you are able to access the web project through
browser.
Note: server will extract the war file internally.
72. How to extract war file manually?
To extract the war file, you need to use -x switch of
jar tool of JDK.
The command to extract the war file.
jar -xvf projectname.war
75. Reading Form Data using Servlet
Servlets handles form data parsing automatically using
the following methods depending on the situation −
getParameter() − You call request.getParameter()
method to get the value of a form parameter.
getParameterValues() − Call this method if the
parameter appears more than once and returns
multiple values, for example checkbox.
getParameterNames() − Call this method if you want a
complete list of all parameters in the current request.
76. Reading Single values:
getParameter()
request.getParameter() method in the servlet class, to
retrieve the input values from HTML page
Returns the value of a request parameter as a
String, or null if the parameter does not exist
Parameters:
name - a String specifying the name of the parameter
Returns:
a String representing the single value of the parameter
79. Reading Multiple values :
getParameterValues
Returns an array of String objects containing all
of the values the given request parameter has, or
null if the parameter does not exist.
Parameters:
name - a String containing the name of the parameter
whose value is requested
Returns:
an array of String objects containing the parameter's
values
82. getParameterNames
Returns an Enumeration of String objects containing
the names of the parameters contained in this
request
85. Servlets - Client HTTP Request
When a browser requests for a web page, it sends
lot of information to the web server which cannot be
read directly because this information travel as a
part of header of HTTP request.
Request headers are indirectly set by the browser
and sent immediately following the initial GET or
POST request line.
The request includes the headers Accept, Accept-
Encoding, Connection, Cookie, Host, Referer and
User-Agent.
86. 1
Accept
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.
2
Accept-Charset
This header specifies the character sets the browser can use to display
the information. For example ISO-8859-1.
3
Accept-Encoding
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.
4
Accept-Language
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
5
Authorization
This header is used by clients to identify themselves when accessing
password-protected Web pages.
Understanding HTTP 1.1 Request Headers
87. 6
Connection
This header indicates whether the client can handle persistent HTTP
connections. 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.
7
Content-Length
This header is applicable only to POST requests and gives the size of the
POST data in bytes.
8
Cookie
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.
10
If-Modified-Since
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.
88. 11
If-Unmodified-Since
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.
12
Referer
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.
13
User-Agent
This header identifies the browser or other client making
the request and can be used to return different content to
different types of browsers.
89. Methods to Reading Request Headers
1
Cookie[] getCookies()
Returns an array containing all of the Cookie objects the
client sent with this request.
2
Enumeration getAttributeNames()
Returns an Enumeration containing the names of the
attributes available to this request.
3
Enumeration getHeaderNames()
Returns an enumeration of all the header names this request
contains.
4
Enumeration getParameterNames()
Returns an Enumeration of String objects containing the
names of the parameters contained in this request
5
HttpSession getSession()
Returns the current session associated with this request, or
if the request does not have a session, creates one.
90. 6
HttpSession getSession(boolean create)
Returns the current HttpSession associated with this
request or, if if there is no current session and value
of create is true, returns a new session.
7
Locale getLocale()
Returns the preferred Locale that the client will accept
content in, based on the Accept-Language header.
8
Object getAttribute(String name)
Returns the value of the named attribute as an Object, or
null if no attribute of the given name exists.
9
ServletInputStream getInputStream()
Retrieves the body of the request as binary data using a
ServletInputStream.
10
String getAuthType()
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.
91. 11
String getCharacterEncoding()
Returns the name of the character encoding used in the body of this
request.
12
String getContentType()
Returns the MIME type of the body of the request, or null if the type is not
known.
13
String getContextPath()
Returns the portion of the request URI that indicates the context of the
request.
14
String getHeader(String name)
Returns the value of the specified request header as a String.
15
String getMethod()
Returns the name of the HTTP method with which this request was made, for
example, GET, POST, or PUT.
16
String getParameter(String name)
Returns the value of a request parameter as a String, or null if the parameter
does not exist.
17
String getPathInfo()
Returns any extra path information associated with the URL the client sent
when it made this request
92. 18
String getProtocol()
Returns the name and version of the protocol the request.
19
String getQueryString()
Returns the query string that is contained in the request URL after the path.
20
String getRemoteAddr()
Returns the Internet Protocol (IP) address of the client that sent the request.
21
String getRemoteHost()
Returns the fully qualified name of the client that sent the request.
22
String getRemoteUser()
Returns the login of the user making this request, if the user has been
authenticated, or null if the user has not been authenticated.
23
String getRequestURI()
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.
24
String getRequestedSessionId()
Returns the session ID specified by the client.
25
String getServletPath()
Returns the part of this request's URL that calls the JSP.
93. 26
String[] getParameterValues(String name)
Returns an array of String objects containing all of the
values the given request parameter has, or null if the
parameter does not exist.
27
boolean isSecure()
Returns a Boolean indicating whether this request was made
using a secure channel, such as HTTPS.
28
int getContentLength()
Returns the length, in bytes, of the request body and made
available by the input stream, or -1 if the length is not known.
29
int getIntHeader(String name)
Returns the value of the specified request header as an int.
30
int getServerPort()
Returns the port number on which this request was received.
94. The SingleThreadModel Interface
The SingleThreadModel interface is defined in
javx.servlet package and it was provided for thread
safety point of view for the servlets and it will make
sure that no two threads will execute concurrently in
the servlet’s service method to make servlets thread
safe.
The servlet programmer should implement
SingleThreadModel interface to ensure that servlet
can handle only one request at a time.
It is a marker interface, means have no methods.
A marker interface does not contain any methods or
variables. It is completely empty interface and for this
reason also known as empty interface.
95. public class MilitarySecrets extends HttpServlet
implements SingleThreadModel { }
The above Servlet MilitarySecrets implements
SingleThreadModel interface.
The affect is at no time two threads (of two visitors)
signal the same Servlet will be active. Other way to say
is, single thread is active – only one visitor at a time is
honoured.
Each thread is a separate process within a process having
its own execution stack and counter etc. One thread’s data
will not go (or mix up) to the other thread. This is taken care
entirely by the JVM. There may be a situation (it is only a
chance) where threads may not work properly and if the
same thing happens in a very critical area like military
secrets sharing. Best solution is to make one thread active at
a time. Then the go is for SingleThreadModel.
97. Introduction to CGI Variables
If you come to Java servlets from traditional CGI, you
are probably used to the idea of "CGI Variables".
These are a somewhat eclectic collection of information
about the request.
Some are derived from the HTTP request line and
headers (e.g. the part of the URI that came after the
question mark and typically contains the form data,
or the Content-Length header), some are derived from
the socket itself (e.g. the name and IP address of the
requesting host), and some are derived from server
installation parameters (e.g. the mapping of URLs to
actual paths).
98. Accessing the Standard CGI
variables
AUTH_TYPE
If an Authorization header was supplied, this variable
gives the scheme
Access it with request.getAuthType()
CONTENT_LENGTH
For POST requests only, this variable stores the
number of bytes of data sent, as given by the Content-
Length request header
CONTENT_LENGTH CGI variable is a string,
just call request.getContentLength(), which returns
an int.
99. CONTENT_TYPE
CONTENT_TYPE designates the MIME type of
attached data, if specified
Access CONTENT_TYPE with
request.getContentType().
DOCUMENT_ROOT
The DOCUMENT_ROOT variable specifies the real
directory corresponding to the URL http://host/
Access it with
getServletContext().getRealPath("/"). Also, you can
use getServletContext().getRealPath
100. PATH_INFO
This variable supplies any path information attached to
the URL after the address of the servlet but before the
query data
Access the value of PATH_INFO by using
request.getPathInfo().
101. PATH_TRANSLATED
PATH_TRANSLATED gives the path information
mapped to a real path on the server
Access this variable by means of
request.getPathTranslated()
QUERY_STRING
For GET requests, this variable gives the attached
data as a single string with values still URL-encoded
you can get it with request.getQueryString()
102. REMOTE_ADDR
This variable designates the IP address of the client
that made the request, as a String (e.g.,
"198.137.241.30").
Access it by calling request.getRemoteAddr()
REMOTE_HOST
REMOTE_HOST indicates the fully qualified domain
name (e.g., whitehouse.gov) of the client that made
the request
access this variable with request.getRemoteHost()
103. REMOTE_USER
If an Authorization header was supplied and decoded
by the server itself, the REMOTE_USER variable
gives the user part, which is useful for session tracking
in protected sites
Access it with request.getRemoteUser()
REQUEST_METHOD
This variable stipulates the HTTP request type, which
is usually GET or POST but is occasionally HEAD,
PUT, DELETE, OPTIONS, or TRACE
Access this variable by means of
request.getMethod()
104. SCRIPT_NAME
This variable specifies the path to the servlet, relative
to the server's root directory.
It can be accessed through request.getServletPath()
SERVER_NAME
SERVER_NAME gives the host name of the server
machine.
It can be accessed by means of
request.getServerName()
105. SERVER_PORT
This variable stores the port the server is listening on
request.getServerPort(), which returns an int.
SERVER_PROTOCOL
The SERVER_PROTOCOL variable indicates the
protocol name and version used in the request line
(e.g., HTTP/1.0 or HTTP/1.1).
Access it by calling request.getProtocol()
106. SERVER_SOFTWARE
This variable gives identifying information about the
Web server.
Access it by means of
getServletContext().getServerInfo().