Introduction to Java Servlets — Servlets in a Nutshell
![]()
In this modern era of the internet, billion bytes of data is generated on a day-to-day basis. To gain access to this humongous amount of data, every person is required to send a request on the network and await a response. Most of us believe in the misconception that all of these web applications are created over web frameworks like HTML, PHP, JavaScript etc. But, did you know, web applications can be based on Java using a service called Java Servlets? In this article, let’s delve deep into Java Servlets and understand how this technology is useful for creating a web application.
Below is the list of topics that I will be covering in this Java Servlets tutorial:
- Introduction to Web
- Web & HTTP
- Introduction to Servlet
- Servlet Architecture
- Steps to Create Servlet
- Generic Servlet
- Servlet Classes & Interfaces
Before we jump into servlets, let’s understand a few fundamentals of Web.
Introduction to Web
Web is basically a system of Internet servers that supports formatted documents. The documents are formatted using a markup language called HTML (HyperText Markup Language) that supports links to other documents, like graphics, audio, and video files.
Web consists of billions of clients and servers connected through wires and wireless networks. First, web clients make requests to a web server. Then, the web server receives the request, finds the resources and returns the response to the client. When a server answers a request, it usually sends some type of content to the client. Then, the client uses a web browser to send a request to the server. The server often sends a response back to the browser with a set of instructions written in HTML. All browsers know how to display HTML pages to the client.
Basically, this is all about the backend working of the WWW (World Wide Web). Now, let’s understand the connectivity between Web & HTTP.
Web & HTTP
A website is a collection of static files i.e. web pages such as HTML pages, images, graphics etc. A Web application is a website with dynamic functionality on the server. Google, Facebook, Twitter are examples of web applications.
So, what is the link between the Web and HTTP? Let’s now find out.
HTTP (Hypertext Transfer Protocol)
- HTTP is a protocol that clients and servers on the web to communicate.
- It is similar to other internet protocols such as SMTP (Simple Mail Transfer Protocol) and FTP (File Transfer Protocol.
- HTTP is a stateless protocol i.e it supports only one request per connection. This means that with HTTP the clients connect to the server to send one request and then disconnect. This mechanism allows more users to connect to a given server over a period of time.
- The client sends an HTTP request and the server answers with an HTML page to the client, using HTTP.
The HTTP request can be made using a variety of methods, but the ones which we use widely are Get and Post. The method name itself tells the server the kind of request that is being made, and how the rest of the message will be formatted.
Now, with the help of the below table, let’s understand the difference between Get and Post methods of HTTP.
Now, that you have learned a few basics of web, let’s jump to the core topic and understand the concept of a servlet.
Java Servlets: Introduction to Servlets
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. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by web servers. It is also a web component that is deployed on the server to create a dynamic web page.
In this figure you can see, a client sends a request to the server and the server generates the response, analyses it and sends the response to the client.
So, before we jump into the depth of Servlets, let’s see the technology that was used before servlets came into the picture.
CGI vs Servlets
Before servlets, we had CGI i.e. Common Gateway Interface. It is a standard way for a Web server to pass a user’s request to an application program and receives the response to forward to the user. When the user requests a Web page, the server sends back the requested page. However, when a user fills out a form on a Web page and sends it in, it is processed by an application program. The Web server typically passes the form information to a small application program. This program processes the data and sends back a confirmation message. This process of passing data back and forth between the server and the application is called the common gateway interface (CGI). It is part of the Web’s Hypertext Transfer Protocol.
But, why did we stopped using it and switched to servlets? Let’s understand this with the help of the below table:
I hope that based on the above comparison, one can conclude, why Servlets are being used for Web Applications. Now, let’s move ahead with this article and understand Servlet Architecture.
Servlet Architecture
The architecture, here, discusses the communication interface, protocol used, requirements of client and server, the programming with the languages and software involved. Basically, it performs the below-mentioned tasks.
- First, it reads the explicit data sent by the clients (browsers). This data can include an HTML form on a Web page, an applet or a custom HTTP client program. It also reads implicit HTTP request data sent by the clients (browsers). This can include cookies, media types and compression schemes the browser understands, and so forth.
- After that, the servlet processes the data and generate the results. This process may require communicating to a database, executing an RMI, invoking a Web service, or computing the response directly.
- After processing, it sends 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), or Excel formats.
- Finally, it also sends the implicit HTTP response to the clients (browsers). This includes telling the browsers or other clients what type of document is being returned.
Now, let’s understand the various methods in the life cycle of a servlet.
Servlet Life Cycle
The Servlet life cycle mainly includes the following four stages,
- Loading a Servlet
- Initializing the Servlet
- Request handling
- Destroying the Servlet
- When the web server (e.g. Apache Tomcat) starts up, the servlet container deploy and loads all the servlets.
- The servlet is initialized by calling the 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.
- The servlet then calls service() method to process a client’s request. This method is invoked to inform the Servlet about the client requests.
- The servlet is terminated by calling the destroy().
- The destroy() method runs only once during the lifetime of a Servlet and signals the end of the Servlet instance.
init() and destroy() methods are called only once. Finally, a servlet is garbage collected by the garbage collector of the JVM. So this concludes the life cycle of a servlet. Now, let me guide you through the steps of creating java servlets.
Steps to Create Servlet
- Create a directory structure
- Create a Servlet
- Compile the Servlet
- Add mappings to the web.xml file
- Start the server and deploy the project
- Access the servlet
Now, based on the above steps, let’s write a program and understand how a servlet works.
To run a servlet program, we should have Apache Tomcat Server installed and configured. Eclipse for Java EE provides in-built Apache Tomcat. Once the server is configured, you can start with your program. One important point to note — for any servlet program, you need 3 files — index.html file, Java class file, and web.xml file. The very first step is to create a Dynamic Web Project and then proceed further.
Now, let’s see how to add 2 numbers using servlets and display the output in the browser.
First, I will write index.html file
Above program creates a form to enter the numbers for the addition operation. Without the Java class file, you can’t perform addition on 2 numbers. So let’s now create a class file.
After writing the Java class file, the last step is to add mappings to the web.xml file. Let’s see how to do that.
The web.xml file will be present in the WEB-INF folder of your web content. If it is not present, then you can click on Deployment Descriptor and click on Generate Deployment Descriptor Stub. Once you get your web.xml file ready, you need to add the mappings to it. Let’s see how mapping is done using the below example:
Once done, you can execute the program by starting the server and get the desired output on the browser.
Let’s take another example where I will be creating a simple login servlet. Again, the very first step will be to write html file.
Next, let’s code the Java Class file.
In the above code, I have set a condition — if username and password are both equal to edureka, only then it will display successfully logged in, else login will be denied.
Let’s add the mappings to the web.xml file now.
So, this is how a servlet is created and configured. Let’s now see what a Generic servlet is and how is it created.
Generic Servlets
A Generic servlet is a protocol-independent servlet that should always override the service() method to handle the client request. The service() method accepts two arguments, ServletRequest object, and ServletResponse object. The request object tells the servlet about the request made by the client while the response object is used to return a response back to the client. GenericServlet is an abstract class and it has only one abstract method, which is service(). That’s why when we create a Generic Servlet by extending the GenericServlet class, we must override the service() method.
Now, let’s see how to create and invoke a Generic servlet. Again I will code 3 files as shown below:
1. HTML file
We are creating an HTML file that will call the servlet once we click on the link on the web page. Create this file in the WebContent folder. The path of this file should look like this: WebContent/index.html
2. Java Class file
Here we will be creating a Generic Servlet by extending GenericServlet class. When creating a GenericServlet, you must override the service() method. Right click on the src folder and create a new class file and name the file as generic. The file path should look like this: Java Resouces/src/default package/generic.java
3. web.xml
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 the welcome page upon clicking the link on index.html, it will map the welcome page to the Servlet class that we have already created above.
After this, start your Tomcat Server and run the servlet. You will get the desired output.
Now, let’s jump into the last section of this article, and see useful classes and interfaces of Java servlets.
Servlet Classes & Interfaces
Servlet API consists of two important packages that encapsulate all the important classes and interfaces, namely:
- javax.servlet
- javax.servlet.http
With the help of below table let’s see some important classes and Interfaces of a servlet.
This brings us to the end of our blog on Introduction to Java Servlets. I hope you found this blog informative and added value to your knowledge.
If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to Edureka’s official site.
Do look out for other articles in this series which will explain the various other aspects of Java.
Что такое servlet в java

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.
Servlet Architecture is can be depicted from the image itself as provided below as follows:

Execution of Servlets basically involves six basic steps:
- The clients send the request to the webserver.
- The web server receives the request.
- The web server passes the request to the corresponding servlet.
- The servlet processes the request and generates the response in the form of output.
- The servlet sends the response back to the webserver.
- 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.
Difference between Servlet and CGI
| Servlet | CGI(Common Gateway Interface) |
|---|---|
| Servlets are portable and efficient. | CGI is not portable |
| In Servlets, sharing data is possible. | In CGI, sharing data is not possible. |
| Servlets can directly communicate with the webserver. | CGI cannot directly communicate with the webserver. |
| Servlets are less expensive than CGI. | CGI is more expensive than Servlets. |
| Servlets can handle the cookies. | CGI cannot handle the cookies. |
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.* |
| ServletConfig | Interface | javax.servlet.* |
Advantages of a Java Servlet
- Servlet is faster than CGI as it doesn’t involve the creation of a new process for every new request received.
- Servlets, as written in Java, are platform-independent.
- Removes the overhead of creating a new process for each request as Servlet doesn’t run in a separate process. There is only a single instance 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.
Что такое сервлет и зачем нужен портлет?
Пишем мы портлеты на Джаве (Java). Что же такое портлет (portlet)? Портлет, это по своей сути -— сервлет (servlet).
Servlet
Это класс, расширяющий HttpServlet, у которого есть два главных метода
void doGet(HttpServletRequest request, HttpServletResponse response)<>
void doPost(HttpServletRequest request, HttpServletResponse response)<>
Не секрет, что браузер может инициировать два вида запроса к серверу: пост (POST) и гет (GET).
Как вы уже догадались, первый метод сработает при запросе GET к сервлету, второй — при запросе POST.
Можно переопределить третий главный метод
void processRequest(HttpServletRequest request, HttpServletResponse response)<>
Он будет обрабатывать и геты и посты, приходящие к сервлету.
Параметры запроса мы вытаскиваем из request, результат записываем в response. Респонс уходит к браузеру клиента.
Можно получить какой-то конкретный параметр, список всех имен, карту (Map).
Map -— это интерфейс, смысл его заключается в том, что он хранит ключ и значение, связанных с ключом. В случае с параметрами запроса, ключом является имя параметра, значением -— значение параметра (железная логика).
Например, пользователь заполнил форму регистрации и отправил её на сервер:
lolik.ru/registrationservlet?name=lolos&surname=lolobot&age=102
Карта параметров будет выглядеть следующим образом:
name->lols
age->102
surname->lolobot
Если интересно, о картах и прочих вкусностях Java SE мы можем поговорить отдельно.
Значениями параметров реквеста могут быть только строки (String), которые можно привести к нужному типу. Очевидно, значение age лучше превратить в целое число (int или Integer).
Посмотрим на метод:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException <
response.setContentType(«text/html;charset=UTF-8»);
PrintWriter out = response.getWriter();
try <
out.println(«»);
out.println(«»);
out.println(«Servlet MyServlet»);
out.println(«»);
out.println(«»);
out.println(«
Servlet MyServlet at » + request.getContextPath () + «
«);
out.println(«»);
out.println(«»);
> finally <
out.close();
>
>
Берём респонс, пихаем в него html и отправляем пользователю.
Ремарка:
Спасибо zer0access за то, что поправил меня. Пройдя по ссылке java.sun.com/javaee/5/docs/api/javax/servlet/http/HttpServlet.html вы увидите, что есть ещё методы, кроме doGet и doPost.
Метод processRequest генерируется рядом IDE, например NetBeans 6.1 Делается это следующим образом:
/**
* Handles the HTTP GET method.
* param request servlet request
* param response servlet response
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException <
processRequest(request, response);
>
/**
* Handles the HTTP POST method.
* param request servlet request
* param response servlet response
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException <
processRequest(request, response);
>
т.е. описав метод processRequest, ваши doPost и doGet отработают единообразно. Если есть разница при вызове doPost или doGet, то использовать processRequest врядли придётся.
Метод service первым принимает запрос, после запрос переправляется нужному doXxx. В service можно сделать какие-то общие операции, например сделать запись в БД, что такой-то пользователь обратился к такому-то сервлету, затем запрос передается на обработку нужному методу сервлета.
zer0access, спасибо тебе.
Всем сервлеты хороши, но только один сервлет может быть на странице. Два сервлета не влезут — слишком важные персоны.
Как же быть, если очень хочется на одну страницу поместить сервлет-калькулятор и сервлет-переводчик?
Portlet
Очень просто — написать два портлета, один будет считать, второй — переводить. Два, три, много портлетов можно поселить на одной странице. Классический портлет в редакции Sun имеет три режима: view, edit, help. Первый — основной, его видит пользователь. В случае калькулятора, в режиме view (просмотр) будут доступны кнопки. В режиме edit (настройки), например, можно задавать тип калькулятора: обычный или научный, с синусами, косинусами и прочими мудрёными вещами. В режиме help (справка)? как вы уже догадались, будет справка по калькулятору.
Режимы view, edit, help отображаются при помощи jsp (java server pages). Они очень-очень похожи на php-страницы:
Вывод в столбик чисел от 1 до 10 включительно.
можно заменить <%%> на <_? ?_> (как тут пхпшный код-то писать?) и разницы не будет (за исключением того, что Джава требует определения типов переменных).
С режимом view и help все понятно, а зачем нужен режим edit? Допустим, У нас на портале есть две группы пользователей: первая — бухгалтеры, вторая — мы с вами, программисты. Бухгалтерам достаточно обычного калькулятора, где есть +,-,*,/, а нам нужно складывать двоичные числа. В этом случае администратор портала для группы бухгалтеров настроит портлет, как обычный калькулятор, а для нашей группы, как научный.
Чувствуете какой кайф?
Портлет, считай, как маленькое веб-приложение, которое можно поместить на страничку портала и настроить (если возможность реализована программистом) под конкретные нужды пользователя. Можно комбинировать разные портлеты на одной странице.
В следующем номере мы поговорим о портлетах более подробно. Я расскажу, как можно за 5 минут настроить сервер приложений, контейнер для портлетов и как отлаживаться на всем этом хозяйстве нажатием одной кнопки.
Что такое servlet в java
A servlet is a small Java program that runs within a Web server. Servlets receive and respond to requests from Web clients, usually across HTTP, the HyperText Transfer Protocol.
To implement this interface, you can write a generic servlet that extends javax.servlet.GenericServlet or an HTTP servlet that extends javax.servlet.http.HttpServlet .
- The servlet is constructed, then initialized with the init method.
- Any calls from clients to the service method are handled.
- The servlet is taken out of service, then destroyed with the destroy method, then garbage collected and finalized.
In addition to the life-cycle methods, this interface provides the getServletConfig method, which the servlet can use to get any startup information, and the getServletInfo method, which allows the servlet to return basic information about itself, such as author, version, and copyright.
Method Summary
| Modifier and Type | Method and Description |
|---|---|
| void | destroy () |
Method Detail
The servlet container calls the init method exactly once after instantiating the servlet. The init method must complete successfully before the servlet can receive any requests.
- Throws a ServletException
- Does not return within a time period defined by the Web server
getServletConfig
Implementations of this interface are responsible for storing the ServletConfig object so that this method can return it. The GenericServlet class, which implements this interface, already does this.
service
This method is only called after the servlet’s init() method has completed successfully.
The status code of the response always should be set for a servlet that throws or sends an error.
Servlets typically run inside multithreaded servlet containers that can handle multiple requests concurrently. Developers must be aware to synchronize access to any shared resources such as files, network connections, and as well as the servlet’s class and instance variables. More information on multithreaded programming in Java is available in the Java tutorial on multi-threaded programming.
getServletInfo
The string that this method returns should be plain text and not markup of any kind (such as HTML, XML, etc.).
destroy
This method gives the servlet an opportunity to clean up any resources that are being held (for example, memory, file handles, threads) and make sure that any persistent state is synchronized with the servlet’s current state in memory.
- Summary:
- Nested |
- Field |
- Constr |
- Detail:
- Field |
- Constr |
Copyright © 1996-2017, Oracle and/or its affiliates. All Rights Reserved. Use is subject to license terms.