Servlet FudamentalsServlet Fudamentals
E-Commerce
Unit-2
Three tier ModelThree tier Model
 By means of a three tier model, we can separate the
business logic of the web application from
“frontend”(web client) to the “backend” (database).
 The First tier- Web Client
◦ Provides a web based GUI displayed through a web browser in
the client computer.
◦ Implementation of the web client in the web application is called
“Web Publishing” and “Client Side Programming”
 The Second tier- Server Side application
◦ Consists of server side applications that run on a web server or a
dedicated application server.
◦ Server side programming techniques are-
 Common Gateway Interface (CGI)
 Active Server Pages(ASP)
 Java Servlets
 The third tier- DBMS
◦ Provides data storage/retrieval services for the second tier so that
dynamic web pages can be created.
◦ To bridge the second tier SSA’s and the backend DBMS, there are
many ways for database connectivity.
◦ Most popular method is by means of JDBC such as JDBC-ODBC(Java
database Connectivity-Open Database Connectivity) bridge.
CGI – Common Gateway InterfaceCGI – Common Gateway Interface
Need for CGINeed for CGI
 HTML/XHTML is static, it is not parameterized;
 using only HTML/XHTML, CSS and JS one can not write
dynamic web pages: pages that look differently depending on
the user who visit it (client, administrator etc.), pages that
display different products depending on what is in a database,
pages that should be displayed depending on the value of
some parameters.
 using only HTML/XHTML, CSS and JS one can not develop
distributed web applications (e-commerce sites, hotel
booking, web search applications etc.)
OverviewOverview
A plain HTML document is static
A CGI program is executed in real-time, so that
it can output dynamic information.
CGI (Common Gateway Interface) is the language
or protocol that the browser uses to
communicate the data from the form to the web
server.
A standard for interfacing external applications
with information servers, such as HTTP or Web
servers.
When the user submits his/her answers on a form,
the browser bundles them up and sends them to
the web server, which passes them on to your CGI
script/program for processing.
◦ The web page itself does not process the data
entered on the form. Neither does the web
server.
A CGI script/program is any program which knows
how to read that bundle of data.
◦ The script/program must build up and return the
html source for a web page
◦ Shell and Perl scripts are easier and are more
commonly used for CGI scripts.
What is CGI?What is CGI?
 a standard protocol for interfacing external application
software with the web server
 developed in 1993 at NCSA (National Center for
Supercomputing Applications)
 CGI 1.1 specified in RFC 3875, 2004
 allows an external executable file to respond to an HTTP
Request from the browser
 CGI defines how information is passed from the web server
to the executable program and how information is passed
from this back to the server
Server-side web programmingServer-side web programming
 the HTTP Response consists of the output of an exernal
program located on the server machine:
browser
web server
HTTP Request
HTTP Response
executable file/CGI,
php file, jsp file, asp
file
Server-side Request
Response Header +
Html file
 2 methods-
◦ Visit Counter
< IMG SRC=“/cgi-bin/visit-counter”>
 This causes the web browser to start a CGI script on the
server side on encountering the <IMG> tag.
◦ HTML Form
 To pass Data from web client to the web Server for data
processing using HTML forms, one can include the CGI
program called “order.pl” in the <FORM> tag.
 <FORM METHOD=“POST” ACTION=“/cgi-bin/order.pl”>
 The Action attribute invokes the CGI script.
 It is a Perl Script called “orde.pl” stored under the “cgi-bin”
directory of the web server.
Drawbacks of CGIDrawbacks of CGI
 because no special web-oriented language is used for
writing CGI scripts (e.g. shell, perl, c/c++, python etc.)
errors are highly probable and so, security
vulnerabilities due to these problems
 usually a new process is created for each run of a CGI
script; this increases the load on the server
 CGI scripts are executable file; they can write/delete
from the local disk, so this is a security vulnerability
Active Server Pages (ASP)Active Server Pages (ASP)
 To develop Interactive web pages, Microsoft introduced
a server side programming tool called ASP.
 ASP is a “scripting” technique that runs on web servers
rather than web clients, unlike JavaScript and VBScript.
It generates dynamic HTML documents for the
web client.
Execution of the ASP Code by the server
returns the corresponding HTML document to
the client.
The server-side code written in ASP can be
embedded in the HTML document, which
allows one to insert it into web pages even
though it is executed on server.
Disadvantages of ASPDisadvantages of ASP
Not a formal programming language, so
debugging can be more difficult.
Not object-oriented
24.1 Introduction24.1 Introduction
◦ Servlets – Web-based solutions
 Secure access to Website
 Interact with databases
 Dynamically generate custom HTML documents
18
Overview of Java ServletOverview of Java Servlet
ServletsServlets
What can you build with Servlets?What can you build with Servlets?
Search Engines
E-Commerce Applications
Shopping Carts
Product Catalogs
Intranet Applications
Groupware Applications:
◦ bulletin boards
◦ file sharing
Servlets vs. CGIServlets vs. CGI
 A Servlet does not run in a
separate process.
 A Servlet stays in memory
between requests.
 A CGI program needs to be
loaded and started for each
CGI request.
 There is only a single instance
of a servlet which answers all
requests concurrently.
Browser 1
Web
Server
Browser 2
Browser N
Perl 1
Perl 2
Perl N
Browser 1
Web
Server
Browser 2
Browser N
Servlet
 Performance
◦ The performance of servlets is superior to CGI because there is no
process creation for each client request.
◦ Each request is handled by the servlet container process.
◦ After a servlet has completed processing a request, it stays resident in
memory, waiting for another request.
 Portability
◦ Like other Java technologies, servlet applications are portable.
 Rapid development cycle
◦ As a Java technology, servlets have access to the rich Java library that
will help speed up the development process.
 Robustness
◦ Servlets are managed by the Java Virtual Machine.
◦ Don't need to worry about memory leak or garbage collection, which
helps you write robust applications.
 Widespread acceptance
◦ Java is a widely accepted technology.
Benefits of Java Servlets
DefinitionsDefinitions
 A servlet is a Java class that can be loaded dynamically
into and run by a special web server.
 This servlet-aware web server, is known as servlet
container.
 Servlets interact with clients via a request-response
model based on HTTP.
 Therefore, a servlet container must support HTTP as
the protocol for client requests and server responses.
 A servlet container also can support similar protocols
such as HTTPS (HTTP over SSL) for secure
transactions.
Servlet Overview and ArchitectureServlet Overview and Architecture
Servlets used when small portion of
content sent to client is static
Java Server Pages (JSPs) used when only
small portion of content set to client is
dynamic, most is static
HyperText Transfer Protocol (HTTP)
Uniform Resource Locator (URL)
Servlets communicate between clients
and servers using HTTP
27
Servlet Overview and ArchitectureServlet Overview and Architecture
Client sends HTTP request
Servlet container receives request,
directs it to the appropriate servlet
Servlet does processing (including
interacting with databases)
Servlet returns results to client in form
of HTML document
28
Browser HTTP
Server
Static
Content
Servlet
Container
HTTP Request
HTTP Response
Servlet
Servlet Container ArchitectureServlet Container Architecture
Servlet APIsServlet APIs
Every servlet must implement
javax.servlet.Servlet interface
Most servlets implement the interface by
extending one of these classes
◦ javax.servlet.GenericServlet
◦ javax.servlet.http.HttpServlet
Initialization
init()
Service
service()
doGet()
doPost()
doDelete()
doHead()
doTrace()
doOptions()
Destruction
destroy()
Concurrent
Threads
of Execution
Servlet Life CycleServlet Life Cycle
Servlet ExampleServlet Example
1: import java.io.*;
2: import javax.servlet.*;
3: import javax.servlet.http.*;
4:
5: public class MyServlet extends HttpServlet
6: {
7: protected void doGet(HttpServletRequest req,
8: HttpServletResponse res)
9: {
10: res.setContentType("text/html");
11: PrintWriter out = res.getWriter();
12: out.println( "<HTML><HEAD><TITLE> Hello You!” +
13: “</Title></HEAD>” +
14: “<Body> HelloYou!!!</BODY></HTML>“ );
14: out.close();
16: }
17: }
An Example of Servlet (I)An Example of Servlet (I)
Lines 1 to 3 import some packages which
contain many classes which are used by
the Servlet (almost every Servlet needs
classes from these packages).
The Servlet class is declared in line 5. Our
Servlet extends javax.servlet.http.HttpServlet,
the standard base class for HTTP Servlets.
In lines 7 through 16 HttpServlet's doGet
method is getting overridden
An Example of Servlet (II)An Example of Servlet (II)
In line 12 we request a PrintWriter object to
write text to the response message.
In line 11 we use a method of the
HttpServletResponse object to set the content
type of the response that we are going to
send. All response headers must be set
before a PrintWriter or ServletOutputStream is
requested to write body data to the
response.
In lines 13 and 14 we use the PrintWriter to
write the text of type text/html (as specified
through the content type).
An Example of Servlet (III)An Example of Servlet (III)
The PrintWriter gets closed in line 15 when
we are finished writing to it.
In lines 18 through 21 we override the
getServletInfo() method which is supposed to
return information about the Servlet, e.g.
the Servlet name, version, author and
copyright notice. This is not required for
the function of the HelloClientServlet but can
provide valuable information to the user of
a Servlet who sees the returned text in the
administration tool of the Web Server.
Server Side Programming: DatabaseServer Side Programming: Database
ConnectivityConnectivity
IntroductionIntroduction
 As most databases are relational, the SQL plays an important role
in web-based database interactions in these e-commerce
applications.
 All types of e-com apps, ranging from B2C applications such as e-
shopping to B2B applications such as virtual marketplace, require
one to connect to and access information from the back end
database system.
An Application Program Interface(API) is a
useful piece of middleware, which provides an
interface that allows one to access the
necessary functionality for that application.
Java provides an API, JDBC, to allow one to
develop web applications that can access and
update backend database systems.
Am imp feature of JDBC is that it is database
independent.
JDBCJDBC
Is an API spec. whose implementation
comes in the form of jdbc drivers.
JDBC API :
◦ java.sql.*
◦ javax.sql.*
JDBC DriverJDBC Driver
Is a bridge s/w between java application
and database s/w.
Is a java class that implements
java.sql.Driver interface.
Why we use JDBC Driver?
JDBC ArchitectureJDBC Architecture
Java code calls JDBC library
JDBC loads a driver
Driver talks to a particular database
Can have more than one driver -> more than one
database
Application JDBC Driver
JDBC DriversJDBC Drivers
Type I: “Bridge”
Type II: “Native”
Type III: “Middleware”
Type IV: “Pure”
Type 1 Driver (Type 1 Driver (jdbc - odbc bridge driver )jdbc - odbc bridge driver )
Java App
that uses
JDBC API
Jdbc
driver
type1
ODBC Driver
for Oracle
ODBC Driver
for MS-
Access
Oracle
DB
MS
Access
Vendor
DB
Library
for Oracle
Vendor
DB
Library
for M S
Access
JDBC Drivers (Fig.)JDBC Drivers (Fig.)
JDBC
Type I
“Bridge”
Type II
“Native”
Type III
“Middleware”
Type IV
“Pure”
ODBC
ODBC
Driver
CLI (.lib)
Middleware
Server
Steps to develop java/jdbc AppSteps to develop java/jdbc App
java.sql
Classes
------------
Types
DriverManager
Date
TimeStamp
Interfaces
---------------
Connection
Statement
ResultSet
Driver
PreparedStatement
CallableStatement
Steps to develop java/jdbc AppSteps to develop java/jdbc App
Load the JDBC Driver class and register
with DriverManager.
Establish the connection with database
s/w.
Prepare Statement object
Execute the query.
Get result and process the result
Close the connection.
Preparing for Your First JDBCPreparing for Your First JDBC
programprogram
To start with:-
Ecom 1
Ecom 1
Ecom 1
Ecom 1

Ecom 1

  • 1.
  • 2.
    Three tier ModelThreetier Model  By means of a three tier model, we can separate the business logic of the web application from “frontend”(web client) to the “backend” (database).  The First tier- Web Client ◦ Provides a web based GUI displayed through a web browser in the client computer. ◦ Implementation of the web client in the web application is called “Web Publishing” and “Client Side Programming”
  • 4.
     The Secondtier- Server Side application ◦ Consists of server side applications that run on a web server or a dedicated application server. ◦ Server side programming techniques are-  Common Gateway Interface (CGI)  Active Server Pages(ASP)  Java Servlets  The third tier- DBMS ◦ Provides data storage/retrieval services for the second tier so that dynamic web pages can be created. ◦ To bridge the second tier SSA’s and the backend DBMS, there are many ways for database connectivity. ◦ Most popular method is by means of JDBC such as JDBC-ODBC(Java database Connectivity-Open Database Connectivity) bridge.
  • 6.
    CGI – CommonGateway InterfaceCGI – Common Gateway Interface
  • 7.
    Need for CGINeedfor CGI  HTML/XHTML is static, it is not parameterized;  using only HTML/XHTML, CSS and JS one can not write dynamic web pages: pages that look differently depending on the user who visit it (client, administrator etc.), pages that display different products depending on what is in a database, pages that should be displayed depending on the value of some parameters.  using only HTML/XHTML, CSS and JS one can not develop distributed web applications (e-commerce sites, hotel booking, web search applications etc.)
  • 8.
    OverviewOverview A plain HTMLdocument is static A CGI program is executed in real-time, so that it can output dynamic information. CGI (Common Gateway Interface) is the language or protocol that the browser uses to communicate the data from the form to the web server. A standard for interfacing external applications with information servers, such as HTTP or Web servers.
  • 9.
    When the usersubmits his/her answers on a form, the browser bundles them up and sends them to the web server, which passes them on to your CGI script/program for processing. ◦ The web page itself does not process the data entered on the form. Neither does the web server. A CGI script/program is any program which knows how to read that bundle of data. ◦ The script/program must build up and return the html source for a web page ◦ Shell and Perl scripts are easier and are more commonly used for CGI scripts.
  • 10.
    What is CGI?Whatis CGI?  a standard protocol for interfacing external application software with the web server  developed in 1993 at NCSA (National Center for Supercomputing Applications)  CGI 1.1 specified in RFC 3875, 2004  allows an external executable file to respond to an HTTP Request from the browser  CGI defines how information is passed from the web server to the executable program and how information is passed from this back to the server
  • 11.
    Server-side web programmingServer-sideweb programming  the HTTP Response consists of the output of an exernal program located on the server machine: browser web server HTTP Request HTTP Response executable file/CGI, php file, jsp file, asp file Server-side Request Response Header + Html file
  • 12.
     2 methods- ◦Visit Counter < IMG SRC=“/cgi-bin/visit-counter”>  This causes the web browser to start a CGI script on the server side on encountering the <IMG> tag. ◦ HTML Form  To pass Data from web client to the web Server for data processing using HTML forms, one can include the CGI program called “order.pl” in the <FORM> tag.  <FORM METHOD=“POST” ACTION=“/cgi-bin/order.pl”>  The Action attribute invokes the CGI script.  It is a Perl Script called “orde.pl” stored under the “cgi-bin” directory of the web server.
  • 13.
    Drawbacks of CGIDrawbacksof CGI  because no special web-oriented language is used for writing CGI scripts (e.g. shell, perl, c/c++, python etc.) errors are highly probable and so, security vulnerabilities due to these problems  usually a new process is created for each run of a CGI script; this increases the load on the server  CGI scripts are executable file; they can write/delete from the local disk, so this is a security vulnerability
  • 14.
    Active Server Pages(ASP)Active Server Pages (ASP)  To develop Interactive web pages, Microsoft introduced a server side programming tool called ASP.  ASP is a “scripting” technique that runs on web servers rather than web clients, unlike JavaScript and VBScript.
  • 15.
    It generates dynamicHTML documents for the web client. Execution of the ASP Code by the server returns the corresponding HTML document to the client. The server-side code written in ASP can be embedded in the HTML document, which allows one to insert it into web pages even though it is executed on server.
  • 16.
    Disadvantages of ASPDisadvantagesof ASP Not a formal programming language, so debugging can be more difficult. Not object-oriented
  • 17.
    24.1 Introduction24.1 Introduction ◦Servlets – Web-based solutions  Secure access to Website  Interact with databases  Dynamically generate custom HTML documents 18
  • 18.
    Overview of JavaServletOverview of Java Servlet
  • 19.
  • 21.
    What can youbuild with Servlets?What can you build with Servlets? Search Engines E-Commerce Applications Shopping Carts Product Catalogs Intranet Applications Groupware Applications: ◦ bulletin boards ◦ file sharing
  • 22.
    Servlets vs. CGIServletsvs. CGI  A Servlet does not run in a separate process.  A Servlet stays in memory between requests.  A CGI program needs to be loaded and started for each CGI request.  There is only a single instance of a servlet which answers all requests concurrently. Browser 1 Web Server Browser 2 Browser N Perl 1 Perl 2 Perl N Browser 1 Web Server Browser 2 Browser N Servlet
  • 24.
     Performance ◦ Theperformance of servlets is superior to CGI because there is no process creation for each client request. ◦ Each request is handled by the servlet container process. ◦ After a servlet has completed processing a request, it stays resident in memory, waiting for another request.  Portability ◦ Like other Java technologies, servlet applications are portable.  Rapid development cycle ◦ As a Java technology, servlets have access to the rich Java library that will help speed up the development process.  Robustness ◦ Servlets are managed by the Java Virtual Machine. ◦ Don't need to worry about memory leak or garbage collection, which helps you write robust applications.  Widespread acceptance ◦ Java is a widely accepted technology. Benefits of Java Servlets
  • 25.
    DefinitionsDefinitions  A servletis a Java class that can be loaded dynamically into and run by a special web server.  This servlet-aware web server, is known as servlet container.  Servlets interact with clients via a request-response model based on HTTP.  Therefore, a servlet container must support HTTP as the protocol for client requests and server responses.  A servlet container also can support similar protocols such as HTTPS (HTTP over SSL) for secure transactions.
  • 26.
    Servlet Overview andArchitectureServlet Overview and Architecture Servlets used when small portion of content sent to client is static Java Server Pages (JSPs) used when only small portion of content set to client is dynamic, most is static HyperText Transfer Protocol (HTTP) Uniform Resource Locator (URL) Servlets communicate between clients and servers using HTTP 27
  • 27.
    Servlet Overview andArchitectureServlet Overview and Architecture Client sends HTTP request Servlet container receives request, directs it to the appropriate servlet Servlet does processing (including interacting with databases) Servlet returns results to client in form of HTML document 28
  • 28.
    Browser HTTP Server Static Content Servlet Container HTTP Request HTTPResponse Servlet Servlet Container ArchitectureServlet Container Architecture
  • 29.
    Servlet APIsServlet APIs Everyservlet must implement javax.servlet.Servlet interface Most servlets implement the interface by extending one of these classes ◦ javax.servlet.GenericServlet ◦ javax.servlet.http.HttpServlet
  • 30.
  • 31.
    Servlet ExampleServlet Example 1:import java.io.*; 2: import javax.servlet.*; 3: import javax.servlet.http.*; 4: 5: public class MyServlet extends HttpServlet 6: { 7: protected void doGet(HttpServletRequest req, 8: HttpServletResponse res) 9: { 10: res.setContentType("text/html"); 11: PrintWriter out = res.getWriter(); 12: out.println( "<HTML><HEAD><TITLE> Hello You!” + 13: “</Title></HEAD>” + 14: “<Body> HelloYou!!!</BODY></HTML>“ ); 14: out.close(); 16: } 17: }
  • 32.
    An Example ofServlet (I)An Example of Servlet (I) Lines 1 to 3 import some packages which contain many classes which are used by the Servlet (almost every Servlet needs classes from these packages). The Servlet class is declared in line 5. Our Servlet extends javax.servlet.http.HttpServlet, the standard base class for HTTP Servlets. In lines 7 through 16 HttpServlet's doGet method is getting overridden
  • 33.
    An Example ofServlet (II)An Example of Servlet (II) In line 12 we request a PrintWriter object to write text to the response message. In line 11 we use a method of the HttpServletResponse object to set the content type of the response that we are going to send. All response headers must be set before a PrintWriter or ServletOutputStream is requested to write body data to the response. In lines 13 and 14 we use the PrintWriter to write the text of type text/html (as specified through the content type).
  • 34.
    An Example ofServlet (III)An Example of Servlet (III) The PrintWriter gets closed in line 15 when we are finished writing to it. In lines 18 through 21 we override the getServletInfo() method which is supposed to return information about the Servlet, e.g. the Servlet name, version, author and copyright notice. This is not required for the function of the HelloClientServlet but can provide valuable information to the user of a Servlet who sees the returned text in the administration tool of the Web Server.
  • 35.
    Server Side Programming:DatabaseServer Side Programming: Database ConnectivityConnectivity
  • 36.
    IntroductionIntroduction  As mostdatabases are relational, the SQL plays an important role in web-based database interactions in these e-commerce applications.  All types of e-com apps, ranging from B2C applications such as e- shopping to B2B applications such as virtual marketplace, require one to connect to and access information from the back end database system.
  • 37.
    An Application ProgramInterface(API) is a useful piece of middleware, which provides an interface that allows one to access the necessary functionality for that application. Java provides an API, JDBC, to allow one to develop web applications that can access and update backend database systems. Am imp feature of JDBC is that it is database independent.
  • 38.
    JDBCJDBC Is an APIspec. whose implementation comes in the form of jdbc drivers. JDBC API : ◦ java.sql.* ◦ javax.sql.*
  • 39.
    JDBC DriverJDBC Driver Isa bridge s/w between java application and database s/w. Is a java class that implements java.sql.Driver interface. Why we use JDBC Driver?
  • 40.
    JDBC ArchitectureJDBC Architecture Javacode calls JDBC library JDBC loads a driver Driver talks to a particular database Can have more than one driver -> more than one database Application JDBC Driver
  • 41.
    JDBC DriversJDBC Drivers TypeI: “Bridge” Type II: “Native” Type III: “Middleware” Type IV: “Pure”
  • 42.
    Type 1 Driver(Type 1 Driver (jdbc - odbc bridge driver )jdbc - odbc bridge driver ) Java App that uses JDBC API Jdbc driver type1 ODBC Driver for Oracle ODBC Driver for MS- Access Oracle DB MS Access Vendor DB Library for Oracle Vendor DB Library for M S Access
  • 43.
    JDBC Drivers (Fig.)JDBCDrivers (Fig.) JDBC Type I “Bridge” Type II “Native” Type III “Middleware” Type IV “Pure” ODBC ODBC Driver CLI (.lib) Middleware Server
  • 44.
    Steps to developjava/jdbc AppSteps to develop java/jdbc App java.sql Classes ------------ Types DriverManager Date TimeStamp Interfaces --------------- Connection Statement ResultSet Driver PreparedStatement CallableStatement
  • 45.
    Steps to developjava/jdbc AppSteps to develop java/jdbc App Load the JDBC Driver class and register with DriverManager. Establish the connection with database s/w. Prepare Statement object Execute the query. Get result and process the result Close the connection.
  • 46.
    Preparing for YourFirst JDBCPreparing for Your First JDBC programprogram To start with:-

Editor's Notes

  • #32 In the Request Processing phase a JSP page is handled exactly like a regular servlet. Servlets follow a three-phase life cycle: initialization, service, and destruction, with initialization and destruction typically performed once, and service performed many times. Initialization is the first phase of the Servlet life cycle and represents the creation and initialization of resources the Servlet may need to service requests. For example open a db connection, read ancillary files, get runtime parameters. All Servlets must implement the javax.servlet.Servlet interface. This interface defines the init() method to match the initialization phase of a Servlet life cycle. When a container loads a Servlet, it invokes the init() method before servicing any requests. The service phase of the Servlet life cycle represents all interactions with requests until the Servlet is destroyed. The Servlet interface matches the service phase of the Servlet life cycle to the service() method. The service() method of a Servlet is invoked once per each request and is responsible for generating the response to that request. By default a Servlet is multi-threaded, meaning that typically only one instance of a Servlet is loaded by a JSP container at any given time. Initialization is done once, and each request after that is handled concurrently by threads executing the Servlet’s service() method. This implies that a developer needs to be careful in synchronizing shared resources. The destruction phase of the Servlet life cycle represents when a Servlet is being removed from use by a container. The Servlet interface defines the destroy() method to correspond to the destruction life cycle phase. Each time a Servlet is about to be removed from use, a container calls the destroy() method, allowing the Servlet to gracefully terminate and tidy up any resources it might have created. For example closing files, db connections. Init() and destroy() methods can be overwritten by the JSP page author. Service() methos is generated automatically during translation phase and should neve be overwritten.