I can serve only
static HTML
pages
Web Server
Application
Not a problem.
I can handle
dynamic
Helper requests
Application
Web Server
machine
The Helper Application is nothing but a SERVLET´
HTTP/1.1 200 OK
Date: Mon, 27 Jul 2009 [Link] GMT
Server: Apache/2.2.14 (Win32)
Last-Modified: Wed, 22 Jul 2009 [Link] GMT
Content-Length: 88
Content-Type: text/html
Connection: Closed
<html>
<body>
<h1>Hello, World!</h1>
</body>
</html>
HTTP/1.1 404 Not Found
Date: Sun, 18 Oct 2012 [Link] GMT
Server: Apache/2.2.14 (Win32)
Content-Length: 230
Connection: Closed
Content-Type: text/html; charset=iso-8859-1
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
<head>
<title>404 Not Found</title>
</head>
<body>
<h1>Not Found</h1>
<p>The requested URL /[Link] was not found on
this server.</p>
</body>
</html>
HTTP/1.1 400 Bad Request
Date: Sun, 18 Oct 2012 [Link] GMT
Server: Apache/2.2.14 (Win32)
Content-Length: 230
Content-Type: text/html; charset=iso-8859-1
Connection: Closed
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
<head>
<title>400 Bad Request</title>
</head>
<body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not understand.</p>
<p>The request line contained invalid characters following the protocol
string.</p>
</body>
</html>
Status-Code = | "407" ; Authentication Required
"100" ; Continue | "408" ; Request Time-out
| "101" ; Switching Protocols
| "409" ; Conflict
| "200" ; OK
| "201" ;Created | "410" ; Gone
| "202" ; Accepted | "411" ; Length Required
| "203" ; Non-Authoritative Information | "412" ; Precondition Failed
| "204" ; No Content | "413" ; Request Entity Too Large
| "205" ; Reset Content | "414" ; Request-URI Too Large
| "206" ; Partial Content
| "415" ; Unsupported Media
| "300" ; Multiple Choices
| "301" ; Moved Permanently
Type
| "302" ; Found | "416" ; Requested range not
| "303" ; See Other satisfiable
| "304" ; Not Modified | "417" ; Expectation Failed
| "305" ; Use Proxy | "500" ; Internal Server Error
| "307" ; Temporary Redirect | "501" ; Not Implemented
| "400" ; Bad Request
| "502" ; Bad Gateway
| "401" ; Unauthorized
| "402" ; Payment Required | "503" ; Service Unavailable
| "403" ; Forbidden | "504" ; Gateway Time-out
| "404" ; Not Found | "505" ; HTTP Version not
| "405" ; Method Not Allowed supported
| "406" ; Not Acceptable | extension-code
Website
Website is a collection of related web pages that may contain text, images,
audio and video. The first page of a website is called home page. Each
website has specific internet address (URL) that you need to enter in your
browser to access a website.
Website is hosted on one or more servers and can be accessed by visiting its
homepage using a computer network. A website is managed by its owner that
can be an individual, company or an organization.
Static website
Static website is the basic type of website that is easy to create. You don't
need the knowledge of web programming and database design to create a
static website. Its web pages are coded in HTML.
The codes are fixed for each page so the information contained in the page
does not change and it looks like a printed page.
Dynamic website is a collection of dynamic web pages whose
content changes dynamically. It accesses content from a database
or Content Management System (CMS). Therefore, when you alter
or update the content of the database, the content of the website
is also altered or updated.
Dynamic website uses client-side scripting or server-side scripting,
or both to generate dynamic content.
Client side scripting generates content at the client computer on
the basis of user input. The web browser downloads the web page
from the server and processes the code within the page to render
information to the user.
In server side scripting, the software runs on the server and
processing is completed in the server then plain pages are sent to
the user.
HTTP (Hyper Text Transfer Protocol)
The Hypertext Transfer Protocol (HTTP) is application-level protocol for
collaborative, distributed, hypermedia information systems. It is the data
communication protocol used to establish communication between client and
server.
HTTP is TCP/IP based communication protocol, which is used to deliver the data
like image files, query results, HTML files etc on the World Wide Web (WWW) with
the default port is TCP 80. It provides the standardized way for computers to
communicate with each other.
● It is the protocol that allows web servers and browsers to exchange data over the
web.
● It is a request response protocol.
● It uses the reliable TCP connections by default on TCP port 80.
● It is stateless means each request is considered as the new request. In other words,
server doesn't recognize the user by default.
The Basic Features of HTTP (Hyper Text Transfer Protocol):
There are three fundamental features that make the HTTP a simple and powerful protocol
used for communication:
● HTTP is media independent: It specifies that any type of media content can be
sent by HTTP as long as both the server and the client can handle the data content.
● HTTP is connectionless: It is a connectionless approach in which HTTP client i.e.,
a browser initiates the HTTP request and after the request is sent the client
disconnects from server and waits for the response.
● HTTP is stateless: The client and server are aware of each other during a current
request only. Afterwards, both of them forget each other. Due to the stateless nature
of protocol, neither the client nor the server can retain the information about different
request across the web pages.
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:
● The Request-line
● The analysis of source IP address, proxy and port
● The analysis of destination IP address, protocol, port and host
● The Requested URI (Uniform Resource Identifier)
● The Request method and Content
● The User-Agent header
● The Connection control header
● The Cache control header
GET/[Link]?
name1=value1&name2=value2
Some other features of GET requests are:
It remains in the browser history
It can be bookmarked
It can be cached
It have length restrictions
It should never be used when dealing with
sensitive data
It should only be used for retrieving the data
Anatomy of Post Request
The query string (name/value pairs) is sent in HTTP
message body for a POST request:
POST/[Link] HTTP/1.1
Host: www. [Link]
name1=value1&name2=value2
As we know, in case of post request original data is
sent in message body. Let's see how information is
passed to the server in case of post request.
Some other features of POST requests are:
This requests cannot be bookmarked
This requests have no restrictions on length of
data
This requests are never cached
This requests do not retain in the browser
history
he HTTP request methods are:
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
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 amount of data can be sent because data is sent in
header.
In case of post request, large amount of data can be sent because data is sent in body.
2) Get request is not secured because data is exposed in URL bar.
Post request is secured because data is not exposed in URL bar.
3) Get request can be bookmarked.
Post request cannot be bookmarked.
4) Get request is idempotent . It means second request will be ignored until response of first
request is delivered
Post request is non-idempotent.
5) Get request is more efficient and used more than Post.
Post request is less efficient and used less than get.
Jav 2 Platform, Enterprise Edition J2EE
• This platform is an architecture for developing,
deploying, and executing applications in a
distributed environment
Enterprise Architecture
• Three fundamental logic layer
1. Presentation layer
2. Business logic layer
3. The data storage and access layer
Enterprise Architecture Type
• The single tier architecture
• The 2-tier architecture
• The 3-tier architecture
• The n-tier architecture
The single tier architecture
• Presentation logic, Business rules and data
access layer in a single computing architecture
The 2-tier architecture
The 3-tier architecture
3-Tier Architecture
MIDDLE TIER/
CLIENT TIER APPLICATION TIER DATA/EIS TIER
Presentation Business
Logic DATA
Logic
Receives request for data,
retrieves it, and returns it
to client
J2EE/ Session 3/Slide 43 of 49
HTML request SQL request
Database
Database
HTML response SQL response
Browser Business logic Data is stored in
handles and data model Databases and
presentation are handled by other
logic dynamically by repositories
Browser talks the middle tier
Web server via
HTTP protocol
Pros:
– Thin clients deployed everywhere
– Zero client management
– Support various client devices
• i.e. Web browsers, phones, handhelds, etc...
Cons:
– Complexity is moved from the client into the
middle-tier
still but it still needs to be addressed
The n-tier architecture
wa ll
Fire
ws er
Bro
Application Logic= Presentation logic + Business Logic
(No physical demarcation between the two)
Infrastructure services provide additional functionalities required by
application, such as messaging services and transactional services.
• 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.
What Is the J2EE?
• Open and standard based platform for
developing, deploying and managing n-tier,
Web-enabled, server-centric, and component-
based enterprise applications
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
• A web application consists of web components,
static resource files such as images, and helper
classes and libraries.
• The web container provides many supporting
services that enhance the capabilities of web
components and make them easier to develop
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.
• web components and static web content files
such as images are called web resources.
• A web module is the smallest deployable and
usable unit of web resources.
JAVA Servlet
Java Servlet
Servlet technology is used to create a web application (resides at
server side and generates a dynamic web page).
Servlet technology is robust and scalable because of java language.
Before Servlet, CGI (Common Gateway Interface) scripting language
was common as a server-side programming language.
However, there were many disadvantages to this technology.
“Servlets are the Java platform technology of choice for extending and
enhancing Web servers. Servlets provide a component-based,
platform-independent method for building Web-based applications,
without the performance limitations of CGI programs. And unlike
proprietary server extension mechanisms (such as the Netscape
Server API or Apache modules), servlets are server- and platform-
independent. This leaves you free to select a "best of breed" strategy
for your servers, platforms, and tools.
CGI (Common 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.
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. The advantages 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: JVM manages Servlets, so we don't need to worry
about the memory leak, garbage collection, etc.
4. Secure: because it uses java language.
What is a Servlet?
Servlet can be described in many ways, depending on the context.
● Servlet is a technology which is used to create a web
application.
● Servlet is an API that provides many interfaces and classes
including documentation.
● Servlet is an interface that must be implemented for creating
any Servlet.
● Servlet is a class that extends the capabilities of the servers and
responds to the incoming requests. It can respond to any
requests.
● Servlet is a web component that is deployed on the server to
create a dynamic web page.
• A servlet is a Java programming language class
that is used to extend the capabilities of
servers that host applications accessed by
means of a request-response programming
model.
• servlets can respond to any type of request,
• The [Link] and [Link]
packages provide interfaces and classes for
writing servlets.
• All servlets must implement the Servlet
interface, which defines life-cycle methods
public class HelloWorld extends HttpServlet {
}
• Java Servlets are programs that run on a Web
or Application server and act as a middle layer
between a request coming from a Web
browser or other HTTP client and databases or
applications on the HTTP server.
• Using Servlets, you can collect input from
users through web page forms, present
records from a database or another source,
and create web pages dynamically.
• 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.
# Invokes the service method, passing a request and
response object.
• HTTP Request and Response
• The browser sends an HTTP request to the Java web
server. The web server checks if the request is for a
servlet. If it is, the servlet container is passed the
request. The servlet container will then find out
which servlet the request is for, and activate that
servlet. The servlet is activated by calling the
[Link]() method.
• Once the servlet has been activated via the service()
method, the servlet processes the request, and
generates a response. The response is then sent
back to the browser.
servlets perform the following major tasks:
1. 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.
2. 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.
3. 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.
4. 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.
5. 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.
• The [Link] and [Link] packages
provide interfaces and classes for writing servlets.
• It provides the framework for all servlets
– [Link]
• Contains generic interfaces and classes that are implemented and extended by
all servlets
– [Link]
• Contains classes that are extended when creating HTTP-specific servlets
• All servlets must implement the Servlet interface,
which defines life-cycle methods.
• When implementing a generic service, you can use or
extend the GenericServlet class provided with the Java
Servlet API.
• The HttpServlet class provides methods, such as doGet
and doPost, for handling HTTP-specific services.
Container
• Servlet don’t have main method. they are under control
of another java application called container
• A servlet container is nothing but a compiled, executable
program. The main function of the container is to load,
initialize and execute servlets.
• Tomcat is an example of container
• When web server gets a request for servlet, server hands
the request to container in which servlet is deployed
• Container gives the servlet the HTTP request and
reaponse and calls the servlet method,
Servlet Life cycle
• A servlet follows a certain life cycle. The servlet
life cycle is managed by the servlet container.
The life cycle contains the following steps:
• Load Servlet Class.
• Create Instance of Servlet.
• Call the servlets init() method.
• Call the servlets service() method.
• Call the servlets destroy() method.
• The Servlet interface provides the following methods that manage the servlet
and its communications with clients.
1. destroy()
Cleans up whatever resources are being held and makes sure that any
persistent state is synchronized with the servlet's current in-memory state.
2. getServletConfig()
Returns a servlet config object, which contains any initialization parameters
and startup configuration for this servlet.
3. getServletInfo()
Returns a string containing information about the servlet, such as its author,
version, and copyright.
4. init(ServletConfig)
Initializes the servlet. Run once before any requests can be serviced.
5. service(ServletRequest, ServletResponse)
Carries out a single request from the client.
Methods of Servlet interface
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 request,ServletResponse
response): provides response for the incoming request. It is
invoked at each request by the web container.
public void destroy(): is invoked only once and indicates that servlet
is being destroyed.
public ServletConfig getServletConfig() : returns the object of
ServletConfig.
public String getServletInfo(): returns information about servlet
such as writer, copyright, version etc.
• A Java Servlet is just an ordinary Java class
which implements the interface
[Link];
• The easiest way to implement this interface is
to extend either the class GenericServlet or
HttpServlet.
GenericServlet
public abstract class GenericServlet
extends [Link]
implements Servlet, ServletConfig,
[Link]
GenericServlet
• Defines a generic, protocol-independent
servlet
• GenericServlet implements the Servlet and
ServletConfig , [Link] interfaces.
• GenericServlet may be directly extended by a
servlet, although it's more common to extend
a protocol-specific subclass such a HttpServlet.
<<Interface>> <<Interface>> <<Interface>>
[Link] [Link] [Link]
init( ) t e g
getInitParameter( )
getServletConfig( getServletContext( )
)
service( ) [Link] getInitParameterNames(
getServletInfo( ) t )
init( )
destroy( ) getServletConfig( ) getServletName( )
service( )
getServletInfo( )
destroy( )
getInitParameter( )
getServletContext( )
getInitParameterNames(
)
getServletName( )
log( )
[Link]
t
doDelete( )
doGet( )
doOptions( )
doPost( )
doPut( )
doTrace( )
getLastModified(
)
service( )
Basic
Servlet
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class SimpleServlet extends GenericServlet {
public void service(ServletRequest request, ServletResponse
response)
throws ServletException, IOException {
// do something in here
}
}
import [Link].*;
import [Link].*;
public class First extends GenericServlet{
public void service(ServletRequest req,ServletResponse res)
throws IOException,ServletException{
[Link]("text/html");
PrintWriter out=[Link]();
[Link]("<html><body>");
[Link]("<b>hello generic servlet</b>");
[Link]("</body></html>");
HttpServlet
• public abstract class HttpServlet extends
GenericServlet implements [Link]
• an HTTP servlet usually does not override the
service() method. Instead, it overrides doGet()
to handle GET requests and doPost() to handle
POST requests
<<Interface>> <<Interface>> <<Interface>>
[Link] [Link] [Link]
init( ) t e g
getInitParameter( )
getServletConfig( getServletContext( )
)
service( ) [Link] getInitParameterNames(
getServletInfo( ) t )
init( )
destroy( ) getServletConfig( ) getServletName( )
service( )
getServletInfo( )
destroy( )
getInitParameter( )
getServletContext( )
getInitParameterNames(
)
getServletName( )
log( )
[Link]
t
doDelete( )
doGet( )
doOptions( )
doPost( )
doPut( )
doTrace( )
getLastModified(
)
service( )
Basic
Servlet
• 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.
• Tan HTTP servlet usually does not override the
service( ) method. Instead, it overrides doGet( ) to
handle GET requests and doPost( ) to handle POST
requests.
• The service( ) method of HttpServlet handles the
setup and dispatching to all the doXXX( ) methods,
which is why it usually should not be overridden
• A subclass of HttpServlet must override at
least one method, usually one of these:
1. doGet(), if the servlet supports HTTP GET
requests
2. doPost(), for HTTP POST requests
3. doPut(), for HTTP PUT requests
4. doDelete(), for HTTP DELETE requests
5. init and destroy, to manage resources that
are held for the life of the servlet
How to write servlet
# Import the appropriate package and classes, including the
following:
import [Link].*;
import [Link].*;
import [Link].*;
# Extend [Link]. For example:
public class HelloWorldServlet extends HttpServlet{
# Implement a service() method.
public void doGet(HttpServletRequest req,
HttpServletResponse res) throws IOException
{
}
# Set the content type, as follows:
[Link]("text/html");
# Get a reference to a [Link] object to use for output,
as follows:
PrintWriter out = [Link]();
# Create some HTML using the println() method on the PrintWriter
object, as shown in the following example:
[Link]("<html><head><title>Hello World!</title></head>");
[Link]("<body><h1>Hello World!</h1></body></html>");
import [Link].*;
import [Link].*;
import [Link].*;
public class SimpleHttpServlet extends HttpServlet {
protected void doGet( HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<html><head><title>Hello World!</title></head>");
[Link]("<body><h1>Hello World!</h1></body></html>");
}
}
If you want to handle both GET and POST request from a given servlet, you can
override both methods, and have one call the other. Here is how:
public class SimpleHttpServlet extends HttpServlet {
protected void doGet( HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
protected void doPost( HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
[Link]().write("GET/POST response");
}
}
• The /WEB-INF/[Link] file contains the Web
Application Deployment Descriptor for your
application.
• is an XML document, and defines everything
about your application that a server needs to
know
How container found the servlet?
• Servlet mapping controls how you access a servlet
• This mapping is specified in the Deployment
Descriptor ([Link]) of a Web Application to specify
which servlet to be called for an incoming URL.
• Servlet can have three names
1. Actual file name
2. Deployment name/secret internal name
3. Public URL name
Deployment Descriptor
• XML file
• Use two XML element to map URL to Servlet
1) public URL to internal name
2)internal name to fully qualified class name
Two DD to map URL to Servelt are
<servlet>:maps internal name to fully qualified class
name
<servlet-mapping>: maps internal name to public URL
• The entry of the <servlet-mapping> element of the
[Link] contains two child elements - <servlet-name> and
<url-pattern>.
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/UserServlet</url-pattern>
</servlet-mapping>
1. <servlet-name> element is used to specify the name of
the servlet, which should be called for an incoming URL
matching the pattern
2. url-pattern specifies the type of urls for which, the servlet
given in servlet-name should be called.
•
• Every <servlet> element will have at least two
child elements - <servlet-name> and <servlet-
class>.
• <servlet-name> specify name of servlet
• <servlet-class> specify fully qualified class
name of the servlet
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app>
<servlet> Declares servlet
abbreviation
<servlet-name>Hello</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet> fully qualified (e.g., [Link])
Maps servlet to URL (rooted at D)
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/MyHelloServlet</url-pattern>
</servlet-mapping>
</web-app>
How container Handel Request?
1. User click a link that has URL to servlet
2. Container see that request is for servlet so the container create two objects:
HttpServletResponse
HttpServletRequest
3. Container finds the correct servlet based on URL in the request, create or
allocates a thread for that request and pass request and response object to
the servlet thread
4. The container calls the servlet’s service() method. depending upon type of
request, the service() method calls either the doGet() or doPost() method
5. doGet() or doPost() method generates the dynamic page and stuff the page into
response object.
6. Thread completes, the container convert the response object into an Http
response, send it back to client and then delete request and response object.
Compiling
javac –classpath
$LIB/[Link]
[Link]
Directory Structure
Create your
web applications
here
Create a directory
D for your
web application
Create “WEB-INF”
under D
Create “classes”
under “WEB-INF”
Directory Structure
(cont.)
Static content in D
Dynamic content
in WEB-INF
[Link] in WEB-INF
Servlets in classes
• Although servlets can respond to any type of
request, they are commonly used to extend
the applications hosted by Web servers. For
such applications, Java Servlet technology
defines HTTP-specific servlet classes.
• 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.
Web Modules
• proxy, gateway, and tunnel.
• A proxy is a
• forwarding agent, receiving requests for a URI in its absolute form,
• rewriting all or part of the message, and forwarding the reformatted
• request toward the server identified by the URI. A gateway is a
• receiving agent, acting as a layer above some other server(s) and, if
• necessary, translating the requests to the underlying server's
• protocol. A tunnel acts as a relay point between two connections
• without changing the messages; tunnels are used when the
• communication needs to pass through an intermediary (such as a
• firewall) even when the intermediary cannot understand the
contents
• of the messages.