Servelets A

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 40

Why to Learn Servlet?

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.
Java Servlets often serve the same purpose as programs implemented
using the Common Gateway Interface (CGI). But Servlets offer several
advantages in comparison with the CGI.
 Performance is significantly better.
 Servlets execute within the address space of a Web server. It is not
necessary to create a separate process to handle each client request.
 Servlets are platform-independent because they are written in Java.
 Java security manager on the server enforces a set of restrictions to
protect the resources on a server machine. So servlets are trusted.
 The full functionality of the Java class libraries is available to a servlet.
It can communicate with applets, databases, or other software via the
sockets and RMI mechanisms that you have seen already.

Applications of Servlet
 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.
 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.
 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.
 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.
 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.
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.

URL (Uniform Resource Locator) 


HTTP, in full HyperText Transfer Protocol, standard application-level
protocol used for exchanging files on the World Wide Web. HTTP runs on
top of the TCP/IP protocol and (later) on the QUIC protocol.

HTTPS Secure

FTP for files on a File Transfer Protocol (FTP)

Uniform Resource Identifier (URI). 

FQDN – FULLY QUALIFIED DOMAIN NAME


Extended Unique Identifier (EUI)

A MAC address (media access control address)


is a 12-digit hexadecimal number assigned to each device connected
to the network.

In IEEE 802 standard, Data Link Layer is divided into two


sublayers – 
1. Logical Link Control(LLC) Sublayer
2. Media Access Control(MAC) Sublayer

network interface card (NIC).


An Individual Address Block (IAB)

Hot Standby Router Protocol (HSRP) 

MAC address is used by the Media Access Control (MAC)


sublayer of the Data-Link Layer. MAC Address is
worldwide unique since millions of network devices exist
and we need to uniquely identify each. 
 The First 6-digits (say 00:40:96) of MAC Address
identifies the manufacturer, called OUI (Organizational
Unique Identifier). 

The rightmost six digits represent Network Interface


Controller, which is assigned by the manufacturer. 

 Personal Area Network (PAN) ...


 Local Area Network (LAN) ...
 Wireless Local Area Network (WLAN) ...
 Campus Area Network (CAN) ...
 Metropolitan Area Network (MAN) ...
 Wide Area Network (WAN) ...
 Storage-Area Network (SAN) ...
 System-Area Network (also known as SAN)
Passive Optical Local Area Network (POLAN)
Enterprise Private Network (EPN)
Virtual Private Network (VPN)
Servlets perform the following major tasks −
 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.
 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.
 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.
 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.
 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.

Servlets Packages
Java Servlets are Java classes run by a web server
that has an interpreter that supports the Java Servlet
specification.
Servlets can be created using
the javax.servlet and javax.servlet.http packages,
which are a standard part of the Java's enterprise
edition, an expanded version of the Java class
library that supports large-scale development
projects.
These classes implement the Java Servlet and JSP
specifications. At the time of writing this tutorial, the
versions are Java Servlet 2.5 and JSP 2.1.
Java servlets have been created and compiled just
like any other Java class. After you install the servlet
packages and add them to your computer's
Classpath, you can compile servlets with the JDK's
Java compiler or any other current compiler.

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.
We have discussed these disadvantages below.
There are many interfaces and classes in the Servlet API
such as Servlet, GenericServlet, HttpServlet,
ServletRequest, ServletResponse, etc.

o Servlet is a technology which is used to create


a web application.
o Servlet is an API that provides many
interfaces and classes including
documentation.
o Servlet is an interface that must be
implemented for creating any Servlet.
o Servlet is a class that extends the capabilities
of the servers and responds to the incoming
requests. It can respond to any requests.
o Servlet is a web component that is deployed
on the server to create a dynamic web page.

What is a 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 elements such as
HTML, CSS, and JavaScript. The web components typically
execute in Web Server and respond to the HTTP request.
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.
As displayed in the above diagram, there are three states of a servlet: new,
ready and end. The servlet is in new state if servlet instance is created. After
invoking the init() method, Servlet comes in the ready state. In the ready
state, servlet performs all the tasks. When the web container invokes the
destroy() method, it shifts to the end state.

1) Servlet class is loaded


The classloader is responsible to load the servlet class. The servlet
class is loaded when the first request for the servlet is received by
the web container.

2) Servlet instance is created


The web container creates the instance of a servlet after loading
the servlet class. The servlet instance is created only once in the
servlet life cycle.

3) init method is invoked


The web container calls the init method only once after creating the servlet
instance. The init method is used to initialize the servlet. It is the life cycle method
of the javax.servlet.Servlet interface. Syntax of the init method is given below:

1. public void init(ServletConfig config) throws ServletException  
4) service method is invoked
The web container calls the service method each time when
request for the servlet is received. If servlet is not initialized, it
follows the first three steps as described above then calls the
service method. If servlet is initialized, it calls the service method.
Notice that servlet is initialized only once. The syntax of the
service method of the Servlet interface is given below:

1. public void service(ServletRequest request, ServletResponse response)   
2.   throws ServletException, IOException  

5) destroy method is invoked


The web container calls the destroy method before removing the
servlet instance from the service. It gives the servlet an
opportunity to clean up any resource for example memory, thread
etc. The syntax of the destroy method of the Servlet interface is
given below:

1. public void destroy()  

Steps to create a servlet example


There are given 6 steps to create a servlet example. These steps
are required for all the servers.

The servlet example can be created by three ways:


1. By implementing Servlet interface,
2. By inheriting GenericServlet class, (or)
3. By inheriting HttpServlet class

The mostly used approach is by extending HttpServlet because it


provides http request specific method such as doGet(), doPost(),
doHead() etc.

1. Create a directory structure


2. Create a Servlet
3. Compile the Servlet
4. Create a deployment descriptor
5. Start the server and deploy the project
6. Access the servlet

Create the deployment descriptor (web.xml


file)
The deployment descriptor is an xml file, from which Web
Container gets the information about the servet to be invoked.
The web container uses the Parser to get the information from the
web.xml file. There are many xml parsers such as SAX, DOM and
Pull.

There are many elements in the web.xml file. Here is given some
necessary elements to run the simple servlet program.

1. <web-app>  
2.   A Web application (Web app) is an application program that is stored on
a remote server and delivered over the Internet through a browser
interface.
3. <servlet>  
4. 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.

The servlet-name element declares a name for this particular


servlet instance. Each servlet instance in a context must have a
unique name. However, the name is only used to associate URL
mappings with this instance, and need not correspond to the
name of the servlet class or the URL of the servlet.
5. <servlet-name>sonoojaiswal</servlet-name>  

6. <servlet-class>DemoServlet</servlet-class>  
7. </servlet>  
8.   
9. <servlet-mapping>  
10. <servlet-name>sonoojaiswal</servlet-name>  
11. <url-pattern>/welcome</url-pattern>  
12. </servlet-mapping>  
13.   
14. </web-app>  

Description of the elements of web.xml file


There are too many elements in the web.xml file. Here is the illustration of some
elements that is used in the above web.xml file. The elements are as follows:

<web-app> represents the whole application.

<servlet> is sub element of <web-app> and represents the servlet.

<servlet-name> is sub element of <servlet> represents the name of the servlet.

<servlet-class> is sub element of <servlet> represents the class of the servlet.


<servlet-mapping> is sub element of <web-app>. It is used to map the servlet.

<url-pattern> is sub element of <servlet-mapping>. This pattern is used at client side to invoke the
servlet.

How to access the servlet


Open broser and write http://hostname:portno/contextroot/urlpatternofservlet. For
example:

1. http://localhost:9999/demo/welcome

How web container handles the servlet


request?
The web container is responsible to handle the
request. Let's see how it handles the request.
o maps the request with the servlet in the web.xml file.
o creates request and response objects for this request
o calls the service method on the thread
o The public service method internally calls the
protected service method
o The protected service method calls the doGet method
depending on the type of request.
o The doGet method generates the response and it is
passed to the client.
o After sending the response, the web container deletes
the request and response objects. The thread is
contained in the thread pool or deleted depends on
the server implementation.

Today we all are aware of the need of creating


dynamic web pages i.e the ones which have the
capability to change the site contents according to
the time or are able to generate the contents
according to the request received by the client. If
you like coding in Java, then you will be happy to
know that using Java there also exists a way to
generate dynamic web pages and that way is Java
Servlet. But before we move forward with our topic
let’s first understand the need for server-side
extensions. 
Servlets are the Java programs that run on the
Java-enabled web server or application server.
They are used to handle the request obtained from
the webserver, process the request, produce the
response, then send a response back to the
webserver. 
Properties of Servlets are as follows:
 Servlets work on the server-side.
 Servlets are capable of handling complex
requests obtained from the webserver.

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.

Now let us do discuss eccentric point that why do


we need For Server-Side extensions?
The server-side extensions are nothing but the
technologies that are used to create dynamic Web
pages. Actually, to provide the facility of dynamic
Web pages, Web pages need a container or Web
server. To meet this requirement, independent Web
server providers offer some proprietary solutions in
the form of APIs(Application Programming
Interface). 
These APIs allow us to build programs that can run
with a Web server. In this case, Java Servlet is also
one of the component APIs of Java Platform
Enterprise Edition which sets standards for
creating dynamic Web applications in Java. 
Before learning about something, it’s important to
know the need for that something, it’s not like that
this is the only technology available for creating
dynamic Web pages. The Servlet technology is
similar to other Web server extensions such
as Common Gateway Interface(CGI) scripts
and Hypertext Preprocessor (PHP). However,
Java Servlets are more acceptable since they solve
the limitations of CGI such as low performance and
low degree scalability.  
What is CGI?
CGI is actually an external application that is written
by using any of the programming languages
like C or C++ and this is responsible for processing
client requests and generating dynamic content. 
In CGI application, when a client makes a request to
access dynamic Web pages, the Web server
performs the following operations :  
 It first locates the requested web page i.e the

required CGI application using URL.


 It then creates a new process to service the

client’s request.
 Invokes the CGI application within the process

and passes the request information to the


application.
 Collects the response from the CGI application.
 Destroys the process, prepares the HTTP
response, and sends it to the client.

So, in CGI server has to create and destroy the process for every request.
It’s easy to understand that this approach is applicable for handling few
clients but as the number of clients increases, the workload on the server
increases and so the time is taken to process requests increases.  
CGI(Common Gateway
Servlet Interface)

Servlets are portable and


efficient. CGI is not portable

In Servlets, sharing data is In CGI, sharing data is not


possible. possible.

Servlets can directly CGI cannot directly


communicate with the communicate with the
webserver. webserver.

Servlets are less expensive CGI is more expensive than


than CGI. Servlets.

Servlets can handle the CGI cannot handle the


cookies. cookies.
Common Gateway Interface(CGI): The Common
Gateway Interface (CGI) provides the middleware
between WWW servers and external databases and
information sources. The World Wide Web
Consortium (W3C) defined the Common Gateway
Interface (CGI) and also defined how a program
interacts with a HyperText Transfer Protocol (HTTP)
server. The Web server typically passes the form
information to a small application program that
processes the data and may send back a
confirmation message. This process or convention
for passing data back and forth between the server
and the application is called the common gateway
interface (CGI). The following image describes how
a web server acts as an intermediate between the
CGI program and the client browser. 
Servlets API’s: 
Servlets are build from two packages: 
 javax.servlet(Basic)

 javax.servlet.http(Advance)

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.*


Component Type Package

ServletConfig Interface javax.servlet.*

 that handles all requests concurrently. This also saves the


memory and allows a Servlet to easily manage the client state.
 It is a server-side component, so Servlet inherits
the security provided by the Web server.
 The API designed for Java Servlet automatically acquires the
advantages of the Java platforms such as platform-
independent and portability. In addition, it obviously can use
the wide range of APIs created on Java platforms such
as JDBC to access the database.
 Many Web servers that are suitable for personal use or low-
traffic websites are offered for free or at extremely cheap
costs eg. Java servlet. However, the majority of commercial-
grade Web servers are rather expensive, with the notable
exception of Apache, which is free.

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.

 It stands for Java Server Pages.


 It is a server side technology.
 It is used for creating web application.
 It is used to create dynamic web content.
 In this JSP tags are used to insert JAVA code into HTML pages.
 It is an advanced version of Servlet Technology.
 It is a Web based technology helps us to create dynamic and platform
independent web pages.
 In this, Java code can be inserted in HTML/ XML pages or both.
 JSP is first converted into servlet by JSP container before processing
the client’s request.
JSP pages are more advantageous than Servlet:
 They are easy to maintain.
 No recompilation or redeployment is required.
 JSP has access to entire API of JAVA .
 JSP are extended version of Servlet.
Features of JSP
 Coding in JSP is easy :- As it is just adding JAVA code to HTML/XML.
 Reduction in the length of Code :- In JSP we use action tags, custom
tags etc.
 Connection to Database is easier :-It is easier to connect website to
database and allows to read or write data easily to the database.
 Make Interactive websites :- In this we can create dynamic web
pages which helps user to interact in real time environment.
 Portable, Powerful, flexible and easy to maintain :- as these are
browser and server independent.
 No Redeployment and No Re-Compilation :- It is dynamic, secure
and platform independent so no need to re-compilation.
 Extension to Servlet :- as it has all features of servlets, implicit objects
and custom tags
JSP syntax

Syntax available in JSP are following

1. Declaration Tag :-It is used to declare variables.


Syntax:-
<%! Dec var %>
Example:-
<%! int var=10; %>

2. Java Scriplets :- It allows us to add any number of JAVA code,


variables and expressions.
Syntax:-
<% java code %>
3. JSP Expression :- It evaluates and convert the expression to a string.
Syntax:-
<%= expression %>
Example:-
<% num1 = num1+num2 %>
4. JAVA Comments :- It contains the text that is added for information
which has to be ignored.
Syntax:-
<% -- JSP Comments %>
Process of Execution

Steps for Execution of JSP are following:-


 Create html page from where request will be sent to server eg
try.html.
 To handle to request of user next is to create .jsp file Eg. new.jsp
 Create project folder structure.
 Create XML file eg my.xml.
 Create WAR file.
 Start Tomcat
 Run Application

Advantages of using JSP


 It does not require advanced knowledge of JAVA
 It is capable of handling exceptions
 Easy to use and learn
 It contains tags which are easy to use and understand
 Implicit objects are there which reduces the length of code
 It is suitable for both JAVA and non JAVA programmer
Disadvantages of using JSP
 Difficult to debug for errors.
 First time access leads to wastage of time
 It’s output is HTML which lacks features.

A Java Server Page life cycle is defined as the process that started with
its creation which later translated to a servlet and afterward servlet
lifecycle comes into play. This is how the process goes on until its
destruction. 
 Translation of JSP page to Servlet
 Compilation of JSP page(Compilation of JSP into test.java)
 Classloading (test.java to test.class)
 Instantiation(Object of the generated Servlet is created)
 Initialization(jspInit() method is invoked by the container)
 Request processing(_jspService()is invoked by the container)
 JSP Cleanup (jspDestroy() method is invoked by the container)
Translation of JSP page to Servlet : 
This is the first step of the JSP life cycle. This translation phase deals with
the Syntactic correctness of JSP. Here test.jsp file is translated to
test.java. 
Compilation of JSP page : 
Here the generated java servlet file (test.java) is compiled to a class file
(test.class). 
Classloading : 
Servlet class which has been loaded from the JSP source is now loaded
into the container. 

Instantiation : 
Here an instance of the class is generated. The container manages one or
more instances by providing responses to requests. 
Initialization : 
jspInit() method is called only once during the life cycle immediately after
the generation of Servlet instance from JSP. 
Request processing : 
_jspService() method is used to serve the raised requests by JSP. It takes
request and response objects as parameters. This method cannot be
overridden. 
JSP Cleanup : 
In order to remove the JSP from the use by the container or to destroy the
method for servlets jspDestroy()method is used. This method is called
once, if you need to perform any cleanup task like closing open files,
releasing database connections jspDestroy() can be overridden. 

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.
So, before creating a Servlet object, let’s first understand the life cycle of the
Servlet object which is actually understanding how the Servlet container manages
the Servlet object.
Stages of the Servlet Life Cycle: The Servlet life cycle mainly goes through four
stages,
 Loading a Servlet.
 Initializing the Servlet.
 Request handling.
 Destroying the Servlet.
Let’s look at each of these stages in details:
1. Loading a Servlet: The first stage of the Servlet lifecycle involves
loading and initializing the Servlet by the Servlet container. The Web
container or Servlet Container can load the Servlet at either of the
following two stages :
 Initializing the context, on configuring the Servlet with a zero or
positive integer value.
 If the Servlet is not preceding stage, it may delay the loading
process until the Web container determines that this Servlet is
needed to service a request.
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, the container uses the no-argument
constructor.
1. 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. 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.
2. 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.
3. 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.
Servlet Life Cycle Methods
There are three life cycle methods of a Servlet :
 init()
 service()
 destroy()
1. 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.
2. //init() method
3.
4. public class MyServlet implements Servlet{
5. public void init(ServletConfig config) throws ServletException {
6. //initialization code
7. }
8. //rest of code
9. }
10. 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.
11. // service() method
12.
13. public class MyServlet implements Servlet{
14. public void service(ServletRequest res, ServletResponse res)
15. throws ServletException, IOException {
16. // request handling code
17. }
18. // rest of code
19. }
20. destroy() method: The destroy() method runs only once during the
lifetime of a Servlet and signals the end of the Servlet instance.
21. //destroy() method
22.
23. public void destroy()
As soon as the destroy() method is activated, the Servlet container
releases the Servlet instance.
Servlet Life Cycle:
Servlet life cycle can be defined as the stages through which the servlet
passes from its creation to its destruction.
The servlet life cycle consists these stages:
 Servlet is borned
 Servlet is initialized
 Servlet is ready to service
 Servlet is servicing
 Servlet is not ready to service
 Servlet is destroyed
Life cycle methods:
Life cycle methods are those methods which are used to control the life
cycle of the servlet. These methods are called in specific order during the
servlets’s entire life cycle.
The class Servlet provides the methods to control and supervise the life
cycle of servlet. There are three life cycle methods in the Servlet interface.
There are as follows:
 init() method :
1. A servlet’s life begins here .
2. This method is called only once to load the servlet.Since it is called
only once in it’s lifetime,therefore “connected architecture” code is
written inside it because we only want once to get connected with
the database.
Now Question Arises is that:-
Q.Why can’t we write connected architecture code inside the
constructor, since constructor also run only once in it’s entire life?
Ans. Suppose if the connection doesn’t get established, then we can
throw an exception from init() and the rest of the steps stop
executing. But in the constructor we can’t use, throw in it’s prototype
otherwise it is an error.
3. This method receives only one parameter, i.e ServletConfig object.
4. This method has the possibility to throw the ServletException.
5. Once the servlet is initialized, it is ready to handle the client request.
6. The prototype for the init() method:
public void init(ServletConfig con)throws ServletException{ }
where con is ServletConfig object
 NOTE:- In programs of servlet,we use non parameterized version of
init()
Servelets JSP

Servlet is a java code. JSP is a HTML based code.

Writing code for servlet is harder than JSP is easy to code as it is java in
JSP as it is HTML in java. HTML.

Servlet plays a controller role in the JSP is the view in the MVC approach
hasMVC approach. for showing output.

JSP is slower than Servlet because


the first step in the hasJSP lifecycle is
the translation of JSP to java code and
Servlet is faster than JSP. then compile.

Servlet can accept all protocol


requests. JSP only accepts HTTP requests.

In Servlet, we can override the In JSP, we cannot override its


service() method. service() method.

In Servlet by default session


management is not enabled, user In JSP session management is
have to enable it explicitly. automatically enabled.

In Servlet we have to implement


everything like business logic and In JSP business logic is separated
presentation logic in just one servlet from presentation logic by using
file. JavaBeansclient-side.

Modification in Servlet is a time-


consuming and compiling task
because it includes reloading,
recompiling, JavaBeans and restarting JSP modification is fast, just need to
the server. click the refresh button.
Servelets JSP

It does not have inbuilt implicit objects. In JSP there are inbuilt implicit objects.

There is no method for running While running the JavaScript at the


JavaScript on the client side in client side in JSP, the client-side
Servlet. validation is used.

Packages can be imported into the


Packages are to be imported on the JSP program(i.e bottom , middleclient-
top of the program. side, or top )

// Import required java libraries


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class


public class HelloWorld extends HttpServlet {
private String message;

public void init() throws ServletException {


// Do required initialization
message = "Hello World";
}
public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");

// Actual logic goes here.


PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}

public void destroy() {


// do nothing.
}
}

You might also like