HOME

TheInfoList



OR:

A Jakarta Servlet, formerly Java Servlet is a
Java Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
software component A software component is a modular unit of software that encapsulates specific functionality. The desired characteristics of a component are reusability and maintainability. Value Components allow software development to assemble software ...
that extends the capabilities of a server. Although servlets can respond to many types of requests, they most commonly implement web containers for hosting
web application A web application (or web app) is application software that is created with web technologies and runs via a web browser. Web applications emerged during the late 1990s and allowed for the server to dynamically build a response to the request, ...
s on
web server A web server is computer software and underlying Computer hardware, hardware that accepts requests via Hypertext Transfer Protocol, HTTP (the network protocol created to distribute web content) or its secure variant HTTPS. A user agent, co ...
s and thus qualify as a server-side servlet
web API A web API is an application programming interface (API) for either a web server or a web browser. As a web development concept, it can be related to a web application's client side (including any web frameworks being used). A server-side web AP ...
. Such web servlets are the
Java Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
counterpart to other dynamic web content technologies such as PHP and ASP.NET.


Introduction

A Jakarta Servlet is a
Java class Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, pro ...
in Jakarta EE that conforms to the Jakarta Servlet API, a standard for implementing Java classes that respond to requests. Servlets could in principle communicate over any client–server protocol, but they are most often used with
HTTP HTTP (Hypertext Transfer Protocol) is an application layer protocol in the Internet protocol suite model for distributed, collaborative, hypermedia information systems. HTTP is the foundation of data communication for the World Wide Web, wher ...
. In principle, any servlets can extend the class; however, realistically speaking, all servlets extend the class. Thus "servlet" is often used as shorthand for "HTTP servlet". Thus, a servlet can be used to add dynamic content to a
web server A web server is computer software and underlying Computer hardware, hardware that accepts requests via Hypertext Transfer Protocol, HTTP (the network protocol created to distribute web content) or its secure variant HTTPS. A user agent, co ...
using the
Java platform Java is a set of computer software and specifications that provides a software platform for developing application software and deploying it in a cross-platform computing environment. Java is used in a wide variety of computing platforms fr ...
. The generated content is commonly
HTML Hypertext Markup Language (HTML) is the standard markup language for documents designed to be displayed in a web browser. It defines the content and structure of web content. It is often assisted by technologies such as Cascading Style Sheets ( ...
, but may be other data such as
XML Extensible Markup Language (XML) is a markup language and file format for storing, transmitting, and reconstructing data. It defines a set of rules for encoding electronic document, documents in a format that is both human-readable and Machine-r ...
and more commonly,
JSON JSON (JavaScript Object Notation, pronounced or ) is an open standard file format and electronic data interchange, data interchange format that uses Human-readable medium and data, human-readable text to store and transmit data objects consi ...
. The Jakarta Servlet API has, to some extent, been superseded by two standard Java technologies for web services: * the Jakarta RESTful Web Services (JAX-RS 2.0) useful for AJAX, JSON and REST services, and * the Jakarta XML Web Services (JAX-WS) useful for
SOAP Soap is a salt (chemistry), salt of a fatty acid (sometimes other carboxylic acids) used for cleaning and lubricating products as well as other applications. In a domestic setting, soaps, specifically "toilet soaps", are surfactants usually u ...
Web Service A web service (WS) is either: * a service offered by an electronic device to another electronic device, communicating with each other via the Internet, or * a server running on a computer device, listening for requests at a particular port over a n ...
s. A is an object that receives a request and generates a response based on that request. The basic Servlet package defines Java objects to represent servlet requests and responses, as well as objects to reflect the servlet's configuration parameters and execution environment. The Servlet
API An application programming interface (API) is a connection between computers or between computer programs. It is a type of software interface, offering a service to other pieces of software. A document or standard that describes how to build ...
, contained in the
Java package A Java package organizes Java classes into namespaces, providing a unique namespace for each type it contains. Classes in the same package can access each other's package-private and protected members. In general, a package can contain the fo ...
hierarchy , defines the expected interactions of the web container and a servlet. The package defines
HTTP HTTP (Hypertext Transfer Protocol) is an application layer protocol in the Internet protocol suite model for distributed, collaborative, hypermedia information systems. HTTP is the foundation of data communication for the World Wide Web, wher ...
-specific subclasses of the GenericServlet. This package includes session management objects that track multiple requests and responses between the web server and a client. Servlets can maintain
state State most commonly refers to: * State (polity), a centralized political organization that regulates law and society within a territory **Sovereign state, a sovereign polity in international law, commonly referred to as a country **Nation state, a ...
in session variables across many server transactions by using HTTP cookies, or URL mapping. There are several ways of creating a servlet and using URL mapping with a servlet. Before servlet 3.0 specification (Tomcat 7.0), configuring the web.xml to map a servlet to a URL was the only option. For applications using the servlet 3.0 specification or later, the @WebServlet annotation can be used to map any servlet to one or more URL patterns. Servlets may be packaged in a WAR file as a
web application A web application (or web app) is application software that is created with web technologies and runs via a web browser. Web applications emerged during the late 1990s and allowed for the server to dynamically build a response to the request, ...
. A web container is required for deploying and running a servlet. A web container (also known as a servlet container) is essentially the component of a web server that interacts with the servlets. The web container is responsible for managing the lifecycle of servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access rights. Servlets can be generated automatically from Jakarta Server Pages (JSP) by the Jakarta Server Pages compiler. The difference between servlets and JSP is that servlets typically embed HTML inside Java code, while JSPs embed Java code in HTML. In general, when using JSPs, embedding Java code in JSP is considered bad practice. Instead, a better approach would be to move the back-end logic from the JSP to the Java code in the Servlet. This ensures that the Servlet is only responsible for processing, and the JSP is only responsible for presenting the HTML, allowing for a clear
separation of concerns In computer science, separation of concerns (sometimes abbreviated as SoC) is a design principle for separating a computer program into distinct sections. Each section addresses a separate '' concern'', a set of information that affects the code o ...
and conformance to the single-responsibility principle. While the direct usage of servlets to generate HTML (as shown in the example below) has become rare, the higher level MVC web framework in Jakarta EE ( Faces) still explicitly uses the servlet technology for the low level request/response handling via the . A somewhat older usage is to use servlets in conjunction with JSPs in a pattern called " Model 2", which is a flavor of the
model–view–controller Model–view–controller (MVC) is a software architectural pattern commonly used for developing user interfaces that divides the related program logic into three interconnected elements. These elements are: * the model, the internal representat ...
.


History

The Java Servlet API was first publicly announced at the inaugural JavaOne conference in May 1996. About two months after the announcements at the conference, the first public implementation was made available on the JavaSoft website. This was the first alpha of the Java Web Server (JWS; then known by its codename ''Jeeves'') which would eventually be shipped as a product on June 5, 1997. In his blog on java.net, Sun veteran and
GlassFish GlassFish is an open-source Jakarta EE platform application server project started by Sun Microsystems, then sponsored by Oracle Corporation, and now living at the Eclipse Foundation and supported by OmniFish, Fujitsu and Payara. The support ...
lead Jim Driscoll details the history of servlet technology.
James Gosling James Arthur Gosling (born 19 May 1955) is a Canadian computer scientist, best known as the founder and lead designer behind the Java (programming language), Java programming language. Gosling was elected a member of the National Academy of E ...
first thought of servlets in the early days of
Java Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
, but the concept did not become a product until December 1996 when Sun shipped JWS. This was before what is now Jakarta EE was made into a specification. The Servlet1 specification was created by Pavni Diwanji while she worked at
Sun Microsystems Sun Microsystems, Inc., often known as Sun for short, was an American technology company that existed from 1982 to 2010 which developed and sold computers, computer components, software, and information technology services. Sun contributed sig ...
, with version 1.0 finalized in June 1997. Starting with version 2.2, the specification was developed under the
Java Community Process The Java Community Process (JCP), established in 1998, is a formal mechanism that enables interested parties to develop standard technical specifications for Java technology. Becoming a member of the JCP requires solid knowledge of the Java program ...
.


Life cycle of a servlet

Three methods are central to the life cycle of a servlet. These are init(), service(), and destroy(). They are implemented by every servlet and are invoked at specific times by the server. * During initialization stage of the servlet life cycle, the web container initializes the servlet instance by calling th
init()
method, passing an object implementing th

interface. This configuration object allows the servlet to access name-value initialization parameters from the web application. * After initialization, the servlet instance can service client requests. Each request is serviced in its own separate thread. The web container calls the service() method of the servlet for every request. The service() method determines the kind of request being made and dispatches it to an appropriate method to handle the request. The developer of the servlet must provide an implementation for these methods. If a request is made for a method that is not implemented by the servlet, the method of the parent class is called, typically resulting in an error being returned to the requester. * Finally, the web container calls the destroy() method that takes the servlet out of service. The destroy() method, like init(), is called only once in the lifecycle of a servlet. The following is a typical user scenario of these methods. # Assume that a user requests to visit a URL. #* The browser then generates an HTTP request for this URL. #* This request is then sent to the appropriate server. # The HTTP request is received by the web server and forwarded to the servlet container. #* The container maps this request to a particular servlet. #* The servlet is dynamically retrieved and loaded into the address space of the container. # The container invokes the init() method of the servlet. #* This method is invoked only when the servlet is first loaded into memory. #* It is possible to pass initialization parameters to the servlet so that it may configure itself. # The container invokes the service() method of the servlet. #* This method is called to process the HTTP request. #* The servlet may read data that has been provided in the HTTP request. #* The servlet may also formulate an HTTP response for the client. # The servlet remains in the container's address space and is available to process any other HTTP requests received from clients. #* The service() method is called for each HTTP request. # The container may, at some point, decide to unload the servlet from its memory. #* The algorithms by which this decision is made are specific to each container. # The container calls the servlet's destroy() method to relinquish any resources such as file handles that are allocated for the servlet; important data may be saved to a persistent store. # The memory allocated for the servlet and its objects can then be garbage collected.


Example

The following example servlet prints how many times its service() method was called. Note that HttpServlet is a subclass of GenericServlet, an implementation of the Servlet interface. The service() method of HttpServlet class dispatches requests to the methods doGet(), doPost(), doPut(), doDelete(), and so on; according to the HTTP request. In the example below service() is overridden and does not distinguish which HTTP request method it serves. import java.io.IOException; import jakarta.servlet.ServletConfig; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; public class ServletLifeCycleExample extends HttpServlet


Container servers

The specification for Servlet technology has been implemented in many products. See a list of implementations on the web container page. There are also other types of servlet containers such as those for SIP servlets, e.g., SailFin.


See also

* Apache JServ Protocol (AJP)


Citations


References

*


Tutorials


How to Start With Servlets Using Jakarta EE 10 , Jakarta EE , The Eclipse Foundation

Jakarta Servlet, Jakarta Faces and Jakarta Server Pages Explained , Jakarta EE , The Eclipse Foundation



External links

*
Servlets.com
{{Authority control Articles with example Java code Servlet Servlet