0% found this document useful (0 votes)
121 views

Servlet Notes

A servlet is a Java program that runs on a web server and is used to develop dynamic web applications. It allows requests from clients to be handled and responses to be generated dynamically. Servlets are better than CGI as they are more efficient, scalable and robust due to being handled by threads instead of processes. The servlet API includes classes for generic and HTTP servlets to create dynamic web applications.

Uploaded by

Senthil Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
121 views

Servlet Notes

A servlet is a Java program that runs on a web server and is used to develop dynamic web applications. It allows requests from clients to be handled and responses to be generated dynamically. Servlets are better than CGI as they are more efficient, scalable and robust due to being handled by threads instead of processes. The servlet API includes classes for generic and HTTP servlets to create dynamic web applications.

Uploaded by

Senthil Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Servlet

Servlet is a java program that runs inside JVM on the web server. It is used
for developing dynamic web applications.
What is dynamic web application?
A web application can be described as collection of web pages (e.g. a
website) and when we call it dynamic,
It simply means that the web pages are not same for all the users, web pages
would be generated on server side based on the request made by client (user’s
browser).
Difference between static and dynamic web page
Static page as name suggests remains same for all users
However a dynamic web page changes based on the request from client
(user’s browser).
Example: consider a web application that shows you two input fields & an
add button and when you enter two numbers and click add, it shows you another
web page that has the result of addition of two numbers, this web application is
dynamic in nature as the second web page that shows you the result changes based
on the user input, it is not static for all users.
CGI (Common Gateway Interface)
CGI has several limitations such as performance, scalability, reusability etc.
that a servlet doesn’t have.
Limitations of CGI
Server has to create a new CGI process for every client request.
Example: If 100 users are accessing the web application, then the server has
to create 100 CGI processes to handle the request made by them. Since a server has
limited resources, creating new process every time for a new request is not a viable
option, this imposed the limitation on server, due to that the server cannot handle
more than a specified number of users at the same time.
How Servlet is better than CGI
CGI programs are handled by a new process every time a new request has
been made.
Unlike CGI, the servlet programs are handled by separate threads that can
run concurrently more efficiently.
CGI program can be written in any programming language that makes it mostly
platform dependent as not all programming languages are platform independent.
Servlet only uses Java as programming language that makes it platform
independent and portable.
Another benefit of using java is that the servlet can take advantage of the
object oriented programming features of java.

How Servlet Works


As I mentioned above that concurrent requests to the server are handled by
threads,

Features of Servlet
1. Portable:
As I mentioned above that Servlet uses Java as a programming language,
Since java is platform independent, the same holds true for servlets.
Example: you can create a servlet on Windows operating system that users
Glass Fish as web server and later run it on any other operating system like Unix,
Linux with Apache tomcat web server,
This feature makes servlet portable and this is the main advantage servlet has
over CGI.
2. Efficient and scalable:
Once a servlet is deployed and loaded on a web server, it can instantly start
fulfilling request of clients.
The web server invokes servlet using a lightweight thread so multiple client
requests can be filling by servlet at the same time using the multithreading feature
of Java.
Compared to CGI where the server has to initiate a new process for every client
request, the servlet is truly efficient and scalable.
3. Robust:
By inheriting the top features of Java (such as Garbage collection, Exception
handling, Java Security Manager etc.)
the servlet is less prone to memory management issues and memory leaks.
This makes development of web application in servlets secure and less error prone.

Servlet API
We need to use Servlet API to create servlets.
There are two packages that you must remember while using API,
1. javax.servlet package that contains the classes to support generic servlet
(protocol-independent servlet)
2. javax.servlet.http package that contains classes to support http servlet.

Let’s see the hierarchy of packages:

java.lang.Object
|_extended by javax.servlet.GenericServlet
|_extended by javax.servlet.http.HttpServlet

Generic Servlet
If you are creating a Generic Servlet then you must
extend javax.servlet.GenericServlet class.
GenericServlet class has an abstract service() method. Which means the
subclass of GenericServlet should always override the service() method.

Signature of service() method:


public abstract void service(ServletRequest request, ServletResponse
response) throws ServletException, java.io.IOException

The service() method accepts two arguments


1. ServletRequest object and
2. ServletResponse object.
The request object tells the servlet about the request made by client
while the response object is used to return a response back to the client.
How Generic Servlet works?

Hierarchy of Generic Servlet


java.lang.Object
|_extended by javax.servlet.GenericServlet
Generic Servlet is an abstract class and it has only one abstract method,
which is service ().
That’s why when we create Generic Servlet by extending Generic Servlet
class, we must override service () method.

Pros of using Generic Servlet:


1. Generic Servlet is easier to write
2. Has simple lifecycle methods
3. To write Generic Servlet you just need to extend
javax.servlet.GenericServlet and override the service() method.

Cons of using Generic Servlet:


Working with Generic Servlet is not that easy because we don’t have
convenience methods such as doGet(), doPost(), doHead() etc in Generic Servlet
that we can use in Http Servlet.
In Http Servlet we need to override particular convenience method for
particular request,
Example:
If you need to get information then override doGet(),
If you want to send information to server override doPost().
However in Generic Servlet we only override service() method for each type of
request which is cumbersome.
Use HttpServlet instead of the GenericServlet.
HttpServlet is easier to work with, and has more methods to work with than
GenericServlet.
HTTP Servlet
If you creating Http Servlet you extend javax.servlet.http.HttpServlet class,
which is an abstract class.
Unlike Generic Servlet, the HTTP Servlet doesn’t override the service()
method.
Instead it overrides one or more of the following methods.
It must override at least one method from the list below:
• doGet() – This method is called by servlet service method to handle the
HTTP GET request from client. The Get method is used for getting
information from the server
• doPost() – Used for posting information to the Server
• doPut() – This method is similar to doPost method but unlike doPost method
where we send information to the server, this method sends file to the server,
this is similar to the FTP operation from client to server
• doDelete() – allows a client to delete a document, webpage or information
from the server
• init() and destroy() – Used for managing resources that are held for the life
of the servlet
• getServletInfo() – Returns information about the servlet, such as author,
version, and copyright
.
In Http Servlet there is no need to override the service() method
As this method dispatches the Http Requests to the correct method handler,
Example: if it receives HTTP GET Request it dispatches the request to the
doGet() method.
Interfaces in javax.servlet package
• Servlet
• ServletRequest
• ServletResponse
• ServletConfig
• ServletContext
• SingleThreadModel
• RequestDispatcher
• ServletRequestListener
• ServletRequestAttributeListener
• ServletContextListener
• ServletContextAttributeListener
• Filter
• FilterConfig
• FilterChain

Classes in javax.servlet package


• GenericServlet
• ServletInputStream
• ServletOutputStream
• ServletException
• ServletRequestWrapper
• ServletRequestEvent
• ServletResponseWrapper
• ServletContextEvent
• ServletRequestAttributeEvent
• ServletContextAttributeEvent
• UnavailableException
Interfaces in javax.servlet.http package
• HttpSession
• HttpServletRequest
• HttpServletResponse
• HttpSessionAttributeListener
• HttpSessionListener
• HttpSessionBindingListener
• HttpSessionActivationListener
• HttpSessionContext
Classes in javax.servlet.http package
• HttpServlet
• Cookie
• HttpSessionEvent
• HttpSessionBindingEvent
• HttpServletRequestWrapper
• HttpServletResponseWrapper
• HttpUtils

How to create and run Servlet in Eclipse IDE


→Installing Eclipse,
→Setting up apache tomcat server and
→Running your first hello world servlet application.
Download Eclipse IDE
Install Eclipse on Windows
Go to this link https://www.eclipse.org/downloads.
Under “Get Eclipse Oxygen”
❯ Click “Download Packages”
❯ Download “Eclipse IDE for Java Developers”.
You would see two options on the right side (32 bit and 64 bit),
Click on 32 bit if you system is 32 bit else click on 64 bit. This will
download a zipped file on your system.
To install Eclipse, unzip the downloaded file and copy the unzipped folder to
the desired location.

Installing and configuring Apache tomcat server in Eclipse


In order to run Servlet in Eclipse IDE, you need to have Apache tomcat
Server configured in Eclipse IDE.

How to configure Apache Tomcat Server in Eclipse IDE


Step 1: Download
Go to this link: http://tomcat.apache.org/download-80.cgi.
If you are on Windows then you have two options,
32 bit and
64 bit, depending on your operating system type click on the zip file,
Example: if you are on 64 bit windows then click on the 64-bit Windows
zip.
Step 2: Extract the downloaded zip folder
Extract the zipped folder to any desired location.
Step 3: Select the Server in Eclipse IDE
Open Eclipse IDE ❯ Click on the Servers tab located at the bottom ❯ right
click ❯ New ❯ click on Server

Select Apache and then


Select the appropriate version of tomcat server,
After selecting, click next.
Note: If you don’t see the apache option in the add server list that means you are
missing few adapters in Eclipse,
Solution – No Apache Tomcat Adapter option in Eclipse IDE
Sometimes you don’t find the Apache option when you try to add the tomcat
server first time in the Eclipse.
It happens when you are missing few adapters.

Step 1: Go to Help ❯ Install New Software

Step 2: In Work with field paste http://download.eclipse.org/releases/mars


Scroll down until you see “Web, XML, Java EE and OSGi Enterprise
Development”, then expand this and add the following adapters:
• JST Server Adapters
• JST Server Adapters Extensions

Step 3: Click Next and you would see the following screen. Click next again.

Step 4: Accept the agreement and click Finish

That’s it. It would ask you to restart the Eclipse after installation, choose
restart. You would now be able to see Apache when you try to add the server in
Eclipse.
Continue to Apache configuration setup -----------------→
You will be presented with a window as shown in the image below. Click
browse and select the folder that you have extracted from the zip file in Step 2.

Click finish.
That’s it you have successfully configured the tomcat server in Eclipse, you
can now run the JSP in Eclipse.
Creating Servlet in Eclipse IDE
Step 1: Create a Project:
Create a Servlet application in Eclipse.
Open Eclipse and then
Click File ❯ New ❯ Click Dynamic Web Project.

If you do not see dynamic web project option in Eclipse

How to fix Dynamic Web Project missing in Eclipse issue


It is frustrating when you want to create your First Servlet project in Eclipse
and don’t find the “dynamic web project” option under project list.
Step 1: Click on Help and then click on “Install New Software”.
Step 2: In Work with paste this link: http://download.eclipse.org/releases/mars
Please note that the link I have provided would work on Eclipse mars only so
change the link according to your Eclipse version,
Step 3: Scroll down to find “Web, XML, Java EE and OSGI Enterprise
Development” option and expand it.

Step 4: Select the following three options under “Web, XML, Java EE and OSGI
Enterprise Development”
• Eclipse Java EE Developer Tools
• Eclipse Java Web Developer Tools
• Eclipse Web Developer Tools
Step 5: Click next and you would see that the software are installing. Wait for
some time and then a popup would ask your permission to restart the Eclipse.
Restart it and you would find the dynamic web project option under project list.

Servlet Create project ---------→


Give Project name and click Next.
Tick the checkbox that says Generate web.xml deployment descriptor

Initial Project structure:


Upon creation of project, the hierarchy (project structure) would look like this:
Step 2: Create a Servlet class:
We are creating a Http Servlet by extending HttpServlet class. Right click on
the src folder and create a new class file, name the file as MyServletDemo. The file
path should look like this: Java Resources/src/default
package/MyServletDemo.java

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

// Extend HttpServlet class to create Http Servlet


public class MyServletDemo extends HttpServlet {

private String mymsg;

public void init() throws ServletException {


mymsg = "Hello World!";
}

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{

// Setting up the content type of webpage


response.setContentType("text/html");

// Writing message to the web page


PrintWriter out = response.getWriter();

out.println("<h1>" + mymsg + "</h1>");


}

public void destroy() {


/* leaving empty for now this can be
* used when we want to do something at the end
* of Servlet life cycle
*/
}
}

Step 3: Create an html page to call the servlet class on a webpage


We are creating an html file that would call the servlet once we click on the link on
web page. Create this file in WebContent folder. The path of the file should look
like this: WebContent/index.html

index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>BeginnersBook Servlet Demo</title>
</head>
<body>
<a href="welcome">Click to call Servlet</a>
</body>
</html>

Edit web.xml file


This file can be found at this path WebContent/WEB-INF/web.xml. In this file we
will map the Servlet with the specific URL. Since we are calling welcome page
upon clicking the link on index.html page so we are mapping the welcome page to
the Servlet class we created above.
<web-app>
<display-name>BeginnersBookDemo</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>

<servlet>
<servlet-name>MyHttpServletDemo</servlet-name>
<servlet-class>MyServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyHttpServletDemo</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
Final Project Structure

Run the project:


Right click on the index.html, run on server.
Click Add All to deploy the Project on Server. Click Finish

Output:

Upon clicking the link you would get this screen:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy