Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 52

Server Side Scripting using

Servlets
CGI Technologies
 The CGI (Common Gateway Interface) is an interface which
handles external programs (CGI scripts) on a web server to
enable the execution of the interactive web pages.
 The common gateway interface provides a consistent way for
data to be passed from the user's request to the application
program and back to the user. 
 One of the examples of CGI flow is the Web browsers send the
forms data to the backend server, and CGI connects to the
application program on the web-server and the program
response to the web browser.
CGI Technologies
 CGI was developed by NCSA (National Center for
Supercomputing Applications) in 1993. It resides in the
server side and enables web browsers to interact with
programs on the web server.
 For example, if a web page queries a database or a user is
submitting the form information to the server at that time
CGI scripts are invoked.
 The server passes that information on to an application in
two ways GET or POST, then the application responds to
the server back to the browser. In this way, browsers get
some results for the user.
Understanding Common Gateway Interface
Advantages

 It is simple.
 CGI is a technology that interfaces with

HTML.
 Speedy since You don’t need to have any

specific particular library to make a CGI


program.
Limitations
 Response time is high.
 The creation of an OS Shell is an heavy weight
activity.
 Not always secure or object-oriented.
 No separation of presentation and business logic.
 Scripting languages are often platform-dependent.
 It uses platform dependent language e.g. C, C++,
perl.
Limitations
 Since the CGI program forks a new process for each
HTTP request, it takes up a lot of server memory.
 It also needs to open a new database connection
each time a request is made, which is again a slow
and costly process.
 Data cannot be cached in memory between page
loads, hence it is less efficient.
Advantages of Servlet over CGI
 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, lighweight, cost of communication between the
threads are low.
 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 no need to worry about momory
leak, garbage collection etc.
 Secure: because it uses java language.
Platform Independindependent. ence

 Servlets are written entirely in java so these


are platform
 Servlets can run on any Servlet enabled web

server.
For example: if you develop an web application
in windows machine running Java web server,
you can easily run the same on apache web
server (if Apache Serve is installed) without
modification or compilation of code.
Performance
 The java servlets runs very fast.
 Servlets run on web server.
 For any program initialization takes significant amount
of time. But in case of servlets initialization takes place
first time it receives a request and remains in memory
till times out or server shut downs. After servlet is
loaded, to handle a new request it simply creates a
new thread and runs service method of servlet.
Safety and Secure

 Java provides very good safety features like memory


management, exception handling etc. Servlets
inherits all these features and emerged as a very
powerful web server extension.
 Servlets are server side components, so it inherits
the security provided by the web server. Servlets are
also benefited with Java Security Manager.
Servlet 
 Java Servlets are part of the Java Enterprise Edition (Java EE).
You will need to run your Java Servlets inside a Servlet
compatible “Servlet Container” (e.g. web server) in order for
them to work.
 Java Servlets it Java technology for creating the dynamic web
applications.
 Java Servlets are server side components in Java that runs on
Servlet enabled web server such as Tomcat, Jetty, WebSphere
etc.
 Java Servlet is much faster then CGI and Perl since it runs in the
same JVM.
Servlet Architecture
Servlets Architecture
 Execution of Servlets basically involves six basic steps: 

1. The clients send the request to the webserver.

2. The web server receives the request.

3. The web server passes the request to the corresponding


servlet.

4. The servlet processes the request and generates the


response in the form of output.

5. The servlet sends the response back to the webserver.

6. The web server sends the response back to the client and
the client browser displays it on the screen
Servlet packaging
 Servlets are build from two packages: 
 javax.servlet(Basic)
 javax.servlet.http(Advance).
Interface
ServletConfig Serializable
SERVLET class

Built in
Generic Servlet class

Http Servlet

UserDefined Servlets
Various classes and interfaces present in
these packages are:
Component Type Package

Servlet Interface javax.servlet.*

ServletRequest Interface javax.servlet.*

ServletResponse Interface javax.servlet.*

GenericServlet Class javax.servlet.*

HttpServlet Class javax.servlet.http.*

HttpServletRequest Interface javax.servlet.http.*

HttpServletResponse Interface javax.servlet.http.*

Filter Interface javax.servlet.*


The Servlet Container
 Servlet container, also known as Servlet engine is an integrated
set of objects that provide a run time environment for Java
Servlet components. 
 In simple words, it is a system that manages Java Servlet
components on top of the Web server to handle the Web client
requests. 
 Services provided by the Servlet container : 
 Network Services: Loads a Servlet class. The loading may be from a local file
system, a remote file system or other network services. The Servlet
container provides the network services over which the request and
response are sent.
 Decode and Encode MIME-based messages: Provides the service of
decoding and encoding MIME-based messages.
 Manage Servlet container: Manages the lifecycle of a Servlet.
 Resource management Manages the static and dynamic resources, such as
HTML files, Servlets, and JSP pages.
 Security Service: Handles authorization and authentication of resource
access.
 Session Management: Maintains a session by appending a session ID to the
URL path.
Basic servlet structure
 To be a servlet, a class should extend HttpServlet and

override doGet or doPost (or both), depending on whether the data is

being sent by GET or by POST.

 These methods take two arguments: an HttpServletRequest and an 

HttpServletResponse.

 The HttpServletRequest has methods that let you find out about

incoming information such as FORM data,HTTP request headers,


 The HttpServletResponse has methods that lets you specify the HTTP

response line , response headers (Content-Type, Set-Cookie, etc.),

and, most importantly,

 lets you obtain a PrintWriter used to send output back to the client.


 Note that doGet and doPost throw two exceptions, so you are

required to include them in the declaration.


 Also note that you have to import classes

in java.io (for PrintWriter, etc.), javax.servlet (for HttpServlet,

etc.),
 and javax.servlet.http (for HttpServletRequest and HttpServletR

esponse).
 Finally,that doGet and doPost are called by the service method,

and sometimes you may want to override service directly, e.g.

for a servlet that handles both GET and POST request.


Basic servlet structure
import java.io.*;

import javax.servlet.*;
import javax.servlet.annotation.*;

import javax.servlet.http.*;

@WebServlet("/hello") // To declare a servlet.


public class HelloWorld extends HttpServlet

{
@Override // use @Override. It helps catch errors where something has caused the class being
extended to change.

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException


{

PrintWriter out = response.getWriter();

out.println("Hello World!");
}
}
 doGet
 Notice that there is no main() method in above program. When user enters a
URL on the address line of browser the browser sends the request and the
servlet’s doGet() method is called by the Container (tomcat).
 doGet method takes two arguments: HttpServletRequest and
HttpServletResponse
 HttpServletRequest lets you get all of the incoming data; like form/query
data, request headers.
 HttpServletResponse lets you send document content and reponse headers
back to the client.
 doGet method throw two execeptions ServletException and IOException you
need to include them in method signature.
 You can get a PrintWriter from the response object. Use the PrintWriter object
to send document content to the browser.
 @WebServlet("/hello")
This is the URL relative to the application. HelloWorld.clsss is invoked
with the URL

•The javax.servlet.annotation package contains a number of annotations that


allow users to use annotations to declare servlets, filters, listeners and specify
the metadata for the declared component.
•Annotations, a form of metadata, provide data about a program that is not
part of the program itself. Annotations have no direct effect on the operation
of the code they annotate.
A Servlet that Generates HTML
 Most servlets generate HTML, not plain text as in the previous
example. To do that, you need two additional steps: tell the
browser that you're sending back HTML, and modify
the println statements to build a legal Web page.
 The first step is done by setting the Content-Type response
header.
 In general, headers can be set via the setHeader method
of HttpServletResponse, but setting the content type is such a
common task that there is also a special setContentType method
just for this purpose. Note that you need to set response
headers before actually returning any of the content via
the PrintWriter. Here's an example:
HTML- Building utilities
 It is a bit cumbersome to generate HTML with println statements. The
real solution is to use Java Server Pages (JSP).
  However, for standard servlets, there are two parts of the Web page
(DOCTYPE and HEAD) that are unlikely to change and thus could
benefit from being incorporated into a simple utility file.
 The DOCTYPE line is technically required by the HTML spec, and
although most major browsers ignore it, it is very useful when sending
pages to formal HTML validators. 

 These validators compare the HTML syntax of pages against the

formal HTML specification, and use the DOCTYPE line to determine


which version of HTML to check against. Their use is very highly
recommended both for static HTML pages and for pages generated via
servlets, so the use of DOCTYPE is well worth the effort, especially if it
can be easily incorporated into a servlet utilities class.
Servlet utilities
Life Cycle Of Servlet
 The entire life cycle of a Servlet is managed by the Servlet
container which uses the javax.servlet.Servlet interface to
understand the Servlet object and manage it.
 The Servlet life cycle mainly goes through four stages,
1. Loading a Servlet.

2. Initializing the Servlet.


3. Request handling.

4. Destroying the Servlet.


 Loading a Servlet: The first
stage of the Servlet lifecycle
involves loading and initializing
the Servlet by the Servlet
container. 
 The Servlet container performs
two operations in this stage :
 Loading : Loads the Servlet
class.
 Instantiation : Creates an
instance of the Servlet. To
create a new instance of the
Servlet,
 Initializing a Servlet: After the Servlet is instantiated successfully,
the Servlet container initializes the instantiated Servlet object.
 The container initializes the Servlet object by invoking
the Servlet.init(ServletConfig) method which accepts ServletConfig
object reference as parameter.
 The Servlet container invokes the Servlet.init(ServletConfig) method
only once, immediately after the Servlet.init(ServletConfig) object is
instantiated successfully.
 public void init(ServletConfig config) throws ServletException  
 This method is used to initialize the resources, such as JDBC
datasource.
 Now, if the Servlet fails to initialize, then it informs the Servlet
container by throwing the ServletException or UnavailableException.
 Handling request: After initialization, the Servlet instance is ready to
serve the client requests. The Servlet container performs the following
operations when the Servlet instance is located to service a request :
◦ It creates the ServletRequest and ServletResponse objects. In this
case, if this is a HTTP request, then the Web container
creates HttpServletRequest and HttpServletResponse objects which
are subtypes of the ServletRequest and ServletResponse objects
respectively.
◦ After creating the request and response objects it invokes the
Servlet.service(ServletRequest, ServletResponse) method by passing
the request and response objects.
 The service() method while processing the request may throw
the ServletException or UnavailableException or IOException.
 Destroying a Servlet: When a Servlet container decides to
destroy the Servlet, it performs the following operations,
◦ It allows all the threads currently running in the service
method of the Servlet instance to complete their jobs and get
released.
◦ After currently running threads have completed their jobs,
the Servlet container calls the destroy() method on the Servlet
instance.
 After the destroy() method is executed, the Servlet container
releases all the references of this Servlet instance so that it
becomes eligible for garbage collection.
 init() method: The Servlet.init() method is called by the Servlet
container to indicate that this Servlet instance is instantiated
successfully and is about to put into service.
 //init() method
 public class MyServlet implements Servlet
 {
 public void init(ServletConfig config)
 throws ServletException
 { //initialization code
 }
 //rest of code }
 service() method: The service() method of the Servlet is invoked to inform
the Servlet about the client requests.This method
uses ServletRequest object to collect the data requested by the client.
 This method uses ServletResponse object to generate the output content.
 // service() method
 public class MyServlet implements Servlet
 {
 public void service(ServletRequest res, ServletResponse res) throws
ServletException, IOException
 {
 // request handling code
 }
 // rest of code
 }
 The service () method is invoked by the container and is called for each
request processed.

- By default the method returns / dispatches the requests to the


appropriate methods, usually a developer’s overridden helper methods
such as doGet() and doPost().
 destroy() method: The destroy() method runs
only once during the lifetime of a Servlet and
signals the end of the Servlet instance.
 //destroy() method
 public void destroy()
 As soon as the destroy() method is activated,
the Servlet container releases the Servlet
instance.
Life Cycle Of Servlet
Single thread model interface
 As Servlets are multithreaded being Java supports multithreading.
Because when a request comes to a WebServer for a Servlet, the
Web Container loads a Servlet, creates a Servlet object, and
executes the callback service() method.
 If one more request comes from another visitor for the same
servlet being executed, the servlet process being executed serves
the other visitor request.
 Here is the one instance where one service() method handles
both the requests. Here, servlet’s multithreading concept comes.
Single thread model interface
 With multiple requests for the same servlet, multiple threads will
be active within the process. If you want to have only one thread
active at a time then you can implement SingleThreadModel
Interface where no methods will be overridden.
 implementing the javax.servlet.SingleThreadModel interface. This
is an empty, tag interface that defines no methods or variables
and serves only to flag the servlet as wanting the alternate life
cycle.
 A server that loads a SingleThreadModel servlet must guarantee,
according to the Servlet API documentation, “that no two threads
will execute concurrently the service method of that servlet.” 
Single thread model interface
 That SingleThreadModel does not solve all thread safety
issues. For example, session attributes and static variables
can still be accessed by multiple requests on multiple threads
at the same time, even when SingleThreadModel servlets are
used.
Handling Client request
 One of the main motivations for building Web pages
dynamically is so that the result can be based upon
user input
 HTML forms, gives details on how to build forms that

collect and transmit data of this sort.


1. Use the FORM element to create an HTML form.
<FORM ACTION="...">...</FORM>
2. Use input elements to collect user data
<INPUT TYPE="TEXT" NAME="...">
3. Place a submit button near the bottom of the form.
For example: <INPUT TYPE="SUBMIT">
Handling Client Request:HTTP Request Headers
 One of the keys to creating effective servlets is understanding how to
manipulate the HyperText Transfer Protocol (HTTP).
 Request headers, are indirectly set by the browser and are sent
immediately following the initial GET or POST request line.
 For instance, the example shows an HTTP request that might result from
a user submitting a book-search request to a servlet at
http://www.somebookstore.com/servlet/Search .

 The request includes the headers Accept, Accept-Encoding, Connection,


Cookie, Host, Referer, and User-Agent, all of which might be important to
the operation of the servlet,
 but none of which can be derived from the form data or deduced
automatically: the servlet needs to explicitly read the request headers to
make use of this information
Handling Client Request:HTTP Request Headers
 GET /servlet/Search?keywords=servlets+jsp HTTP/1.1
 Accept: image/gif, image/jpg, */*
 Accept-Encoding: gzip
 Connection: Keep-Alive
 Cookie: userID=id456578
 Host: www.somebookstore.com
 Referer: http://www.somebookstore.com/findbooks.html
 User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows
NT 5.0)
Reading Request Headers
 Reading headers is straightforward; just call the getHeader method of
Http-ServletRequest with the name of the header. This call returns a
String if the specified header was supplied in the current request, null.

getCookies The getCookies method returns the contents of the


Cookie header, parsed and stored in an array of Cookie
objects.
getContentLength The getContentLength method returns the value of the
Content-Length header (as an int).
getContentType The getContentType method returns the value of the
Content-Type header (as a String).
getDateHeader and The getDateHeader and getIntHeader methods read the
getIntHeader specified headers and then convert them to Date and int
values, respectively.
getHeaderNames Rather than looking up one particular header, you can
use the
getMethod
The getMethod method returns the main request method (normally, GET or
POST, but methods like HEAD, PUT, and DELETE are possible).
getRequestURI
The getRequestURI method returns the part of the URL that comes after the
host and port but before the form data.
For example, for a URL of
http://randomhost.com/servlet/search.BookSearch?subject=jsp,
getRequestURI would return "/servlet/search.BookSearch".
getQueryString
The getQueryString method returns the form data. For example,
with http://randomhost.com/servlet/search.BookSearch?subject=jsp,
getQueryString would return "subject=jsp".
getProtocol
The getProtocol method returns the third part of the request line,
which is generally HTTP/1.0 or HTTP/1.1. Servlets should usually
check getProtocol before specifying response headers that are specific to
Making a Table of All Request Headers

You might also like