Jakarta Servlet

Last updated
Original author(s) Pavni Diwanji
Developer(s) Eclipse Foundation
Initial releaseDecember 1996;27 years ago (1996-12)
Stable release
6.0 / May 31, 2022;21 months ago (2022-05-31)
Repository
Written in Java
Platform Jakarta EE
Size 2.56 MB
Type Software component for Web API
License Eclipse Public License
Website jakarta.ee/specifications/servlet/
Life of a JSP file JSPLife.png
Life of a JSP file

A Jakarta Servlet, formerly Java Servlet is a Java software component 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 applications on web servers and thus qualify as a server-side servlet web API. Such web servlets are the Java counterpart to other dynamic web content technologies such as PHP and ASP.NET.

Contents

Introduction

A Jakarta Servlet is a Java class [1] in Jakarta EE that conforms to the Jakarta Servlet API, [2] 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. In principle, any servlets can extend the GenericServlet class; however, realistically speaking, all servlets extend the HttpServlet class. [3] Thus "servlet" is often used as shorthand for "HTTP servlet". [4] Thus, a servlet can be used to add dynamic content to a web server using the Java platform. [5] The generated content is commonly HTML, but may be other data such as XML and more commonly, JSON.

The Jakarta Servlet API has, to some extent, been superseded[ citation needed ] by two standard Java technologies for web services:

A Servlet 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, contained in the Java package hierarchy javax.servlet , defines the expected interactions of the web container and a servlet. [4]

The package javax.servlet.http defines HTTP-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 in session variables across many server transactions by using HTTP cookies, or URL mapping. The application can keep track of session and cookies by using sessions and cookies. [6] There are several ways for creating and URL mapping for 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. [7]

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. [1] 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. [8] Instead, a better approach would be to move the back-end logic from the JSP to the Java code in the Servlet. [8] This ensures that the Servlet is only responsible for processing, and the JSP is only responsible for presenting the HTML, [8] allowing for a clear separation of concerns 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 FacesServlet .

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.

History

The Java Servlet API was first publicly announced at the inaugural JavaOne conference in May 1996. [9] [10] 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) [11] which would eventually be shipped as a product on June 5, 1997. [12]

In his blog on java.net, Sun veteran and GlassFish lead Jim Driscoll details the history of servlet technology. [13] James Gosling first thought of servlets in the early days of Java, but the concept did not become a product until December 1996 when Sun shipped JWS. [14] [15] [16] This was before what is now the Jakarta EE was made into a specification.

The Servlet1 specification was created by Pavni Diwanji [17] [18] while she worked at Sun Microsystems, with version 1.0 finalized in June 1997. Starting with version 2.2, the specification was developed under the Java Community Process.

Servlet API history
Servlet API versionReleasedSpecificationPlatformImportant Changes
Jakarta Servlet 6.0May 31, 2022 6.0 Jakarta EE 10remove deprecated features and implement requested enhancements
Jakarta Servlet 5.0Oct 9, 2020 5.0 Jakarta EE 9API moved from package javax.servlet to jakarta.servlet
Jakarta Servlet 4.0.3Sep 10, 2019 4.0 Jakarta EE 8Renamed from "Java" trademark
Java Servlet 4.0Sep 2017 JSR 369 Java EE 8 HTTP/2
Java Servlet 3.1May 2013 JSR 340 Java EE 7Non-blocking I/O, HTTP protocol upgrade mechanism (WebSocket) [19]
Java Servlet 3.0 December 2009 JSR 315 Java EE 6, Java SE 6Pluggability, Ease of development, Async Servlet, Security, File Uploading
Java Servlet 2.5 September 2005 JSR 154Java EE 5, Java SE 5Requires Java SE 5, supports annotation
Java Servlet 2.4 November 2003 JSR 154 J2EE 1.4, J2SE 1.3web.xml uses XML Schema
Java Servlet 2.3 August 2001 JSR 53 J2EE 1.3, J2SE 1.2Addition of Filter
Java Servlet 2.2 August 1999 JSR 902, JSR 903 J2EE 1.2, J2SE 1.2Becomes part of J2EE, introduced independent web applications in .war files
Java Servlet 2.1 November 1998 2.1a UnspecifiedFirst official specification, added RequestDispatcher, ServletContext
Java Servlet 2.0December 1997JDK 1.1Part of April 1998 Java Servlet Development Kit 2.0 [20]
Java Servlet 1.0December 1996Part of June 1997 Java Servlet Development Kit (JSDK) 1.0 [14]

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.

The following is a typical user scenario of these methods.

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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.
  7. 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.
  8. 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.

importjava.io.IOException;importjakarta.servlet.ServletConfig;importjakarta.servlet.ServletException;importjakarta.servlet.http.HttpServlet;importjakarta.servlet.http.HttpServletRequest;importjakarta.servlet.http.HttpServletResponse;publicclassServletLifeCycleExampleextendsHttpServlet{privateIntegersharedCounter;@Overridepublicvoidinit(finalServletConfigconfig)throwsServletException{super.init(config);getServletContext().log("init() called");sharedCounter=0;}@Overrideprotectedvoidservice(finalHttpServletRequestrequest,finalHttpServletResponseresponse)throwsServletException,IOException{getServletContext().log("service() called");intlocalCounter;synchronized(sharedCounter){sharedCounter++;localCounter=sharedCounter;}response.getWriter().write("Incrementing the count to "+localCounter);// accessing a local variableresponse.getWriter().flush();// flush response}@Overridepublicvoiddestroy(){getServletContext().log("destroy() called");}}

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.

Citations

  1. 1 2 Murach & Urban 2014, pp. 170–171, §2 Essential servlet and JSP skills - Perspective - Summary.
  2. "Servlet (Java(TM) EE 7 Specification APIs)". oracle.com. Retrieved 2018-07-25.
  3. Murach & Urban 2014, pp. 128–129, §2 Essential servlet and JSP skills - How to create and map a servlet.
  4. 1 2 "Servlet Essentials - Chapter 1". novocode.com. Archived from the original on 2017-12-18.
  5. Murach & Urban 2014, pp. 40–42, §1 Get started right - The servlet for back-end processing.
  6. Murach & Urban 2014, p. 87, §2 Essential servlet and JSP skills.
  7. Murach & Urban 2014, p. 74, §1 Get started right - Other skills for working with web applications.
  8. 1 2 3 Murach & Urban 2014, pp. 46–47, §1 Get started right - The JSP for the second page.
  9. Freedman, Matt (June 26, 1996). "JavaOne conference report". JavaWorld .
  10. Diwanji, Pavani; Connelly, Dave; Wagle, Prasad (May 29, 1996). "Java Server and Servlets" (PDF). Servers and Server Extensions. JavaOne 1996. Archived (PDF) from the original on 2000-08-16. Retrieved 2020-02-01.
  11. Chang, Phil Inje (July 1, 1997). "Interview: The Java Web Server team gives you the skinny". JavaWorld . Retrieved 2018-07-25.
  12. Chang, Phil Inje (June 1, 1997). "Java Web Server ships!". JavaWorld . Retrieved 2018-07-25.
  13. "Servlet History | community.oracle.com". Weblogs.java.net. 2005-12-10. Archived from the original on 2020-08-15. Retrieved 2013-06-14.
  14. 1 2 Hunter, Jason (March 2000). "Servlet Timeline". Beyond Java Servlet Programming. O'Reilly Conference on Java. O'Reilly Media.
  15. "Java Web Server". Javasoft. Sun Microsystems. Archived from the original on 1998-01-11. Retrieved 2020-02-01.
  16. "Java Web Server(tm)". Sun Microsystems. Archived from the original on 2002-02-06. Retrieved 2020-02-01.
  17. "Pavni Diwanji". Family Online Safety Institute. Archived from the original on 26 July 2018. Retrieved 12 November 2016.
  18. USpatent 5928323, Gosling, James A.; Diwanji, Pavni& Connelly, David W.,"Apparatus and method for dynamically generating information with server-side software objects",published 1999-07-27,issued 1999-07-27, assigned to Sun Microsystems
  19. "What's new in Servlet 3.1 ? - Java EE 7 moving forward (Arun Gupta, Miles to go ...)". oracle.com. Retrieved 22 November 2016.
  20. Crawford, William; Hunter, Jason (November 1998). "Preface". Java Servlet Programming (1st ed.). O'Reilly Media. p. ix–x. ISBN   978-1-56592-391-1. We cover Version 2.0 of the Servlet API, which was introduced as part of the Java Web Server 1.1 in December 1997 and clarified by the release of the Java Servlet Development Kit 2.0 in April 1998.
  21. Murach & Urban 2014, pp. 160–163, §15 How to develop servlet - More skills for working with servlets.

Related Research Articles

<span class="mw-page-title-main">Java (programming language)</span> Object-oriented programming language

Java is a high-level, class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible. It is a general-purpose programming language intended to let programmers write once, run anywhere (WORA), meaning that compiled Java code can run on all platforms that support Java without the need to recompile. Java applications are typically compiled to bytecode that can run on any Java virtual machine (JVM) regardless of the underlying computer architecture. The syntax of Java is similar to C and C++, but has fewer low-level facilities than either of them. The Java runtime provides dynamic capabilities that are typically not available in traditional compiled languages.

Jakarta Enterprise Beans is one of several Java APIs for modular construction of enterprise software. EJB is a server-side software component that encapsulates business logic of an application. An EJB web container provides a runtime environment for web related software components, including computer security, Java servlet lifecycle management, transaction processing, and other web services. The EJB specification is a subset of the Java EE specification.

The Jakarta Transactions, one of the Jakarta EE APIs, enables distributed transactions to be done across multiple X/Open XA resources in a Java environment. JTA was a specification developed under the Java Community Process as JSR 907. JTA provides for:

<span class="mw-page-title-main">Jakarta EE</span> Set of specifications extending Java SE

Jakarta EE, formerly Java Platform, Enterprise Edition and Java 2 Platform, Enterprise Edition (J2EE), is a set of specifications, extending Java SE with specifications for enterprise features such as distributed computing and web services. Jakarta EE applications are run on reference runtimes, which can be microservices or application servers, which handle transactions, security, scalability, concurrency and management of the components they are deploying.

Jakarta Server Pages is a collection of technologies that helps software developers create dynamically generated web pages based on HTML, XML, SOAP, or other document types. Released in 1999 by Sun Microsystems, JSP is similar to PHP and ASP, but uses the Java programming language.

The Jakarta Project created and maintained open source software for the Java platform. It operated as an umbrella project under the auspices of the Apache Software Foundation, and all Jakarta products are released under the Apache License. As of December 21, 2011 the Jakarta project was retired because no subprojects were remaining.

A web container is the component of a web server that interacts with Jakarta Servlets. A 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. A web container handles requests to servlets, Jakarta Server Pages (JSP) files, and other types of files that include server-side code. The Web container creates servlet instances, loads and unloads servlets, creates and manages request and response objects, and performs other servlet-management tasks. A web container implements the web component contract of the Jakarta EE architecture. This architecture specifies a runtime environment for additional web components, including security, concurrency, lifecycle management, transaction, deployment, and other services.

<span class="mw-page-title-main">Apache Tomcat</span> Java-based HTTP web server environment

Apache Tomcat is a free and open-source implementation of the Jakarta Servlet, Jakarta Expression Language, and WebSocket technologies. It provides a "pure Java" HTTP web server environment in which Java code can also run. Thus it is a Java web application server, although not a full JEE application server.

Jakarta Faces, formerly Jakarta Server Faces and JavaServer Faces (JSF) is a Java specification for building component-based user interfaces for web applications. It was formalized as a standard through the Java Community Process as part of the Java Platform, Enterprise Edition. It is an MVC web framework that simplifies the construction of user interfaces (UI) for server-based applications by using reusable UI components in a page.

<span class="mw-page-title-main">Apache Struts 1</span> Open-source web application framework

Apache Struts 1 is an open-source web application framework for developing Java EE web applications. It uses and extends the Java Servlet API to encourage developers to adopt a model–view–controller (MVC) architecture. It was originally created by Craig McClanahan and donated to the Apache Foundation in May 2000. Formerly located under the Apache Jakarta Project and known as Jakarta Struts, it became a top-level Apache project in 2005.

Java Management Extensions (JMX) is a Java technology that supplies tools for managing and monitoring applications, system objects, devices and service-oriented networks. Those resources are represented by objects called MBeans. In the API, classes can be dynamically loaded and instantiated. Managing and monitoring applications can be designed and developed using the Java Dynamic Management Kit.

<span class="mw-page-title-main">JSP model 2 architecture</span>

JSP Model 2 is a complex design pattern used in the design of Java Web applications which separates the display of content from the logic used to obtain and manipulate the content. Since Model 2 drives a separation between logic and display, it is usually associated with the model–view–controller (MVC) paradigm. While the exact form of the MVC "Model" was never specified by the Model 2 design, a number of publications recommend a formalized layer to contain MVC Model code. The Java BluePrints, for example, originally recommended using EJBs to encapsulate the MVC Model.

Jakarta XML RPC allows a Jakarta EE application to invoke a Java-based web service with a known description while still being consistent with its WSDL description. JAX-RPC is one of the Java XML programming APIs. It can be seen as Java RMIs over web services. JAX-RPC 2.0 was renamed JAX-WS 2.0. JAX-RPC 1 is deprecated with Java EE 6. The JAX-RPC service utilizes W3C standards like WSDL . The core API classes are located in the Java package javax.xml.rpc.

The Jakarta Standard Tag Library is a component of the Java EE Web application development platform. It extends the JSP specification by adding a tag library of JSP tags for common tasks, such as XML data processing, conditional execution, database access, loops and internationalization.

In software engineering, a WAR file is a file used to distribute a collection of JAR-files, JavaServer Pages, Java Servlets, Java classes, XML files, tag libraries, static web pages and other resources that together constitute a web application.

The Spring Framework is an application framework and inversion of control container for the Java platform. The framework's core features can be used by any Java application, but there are extensions for building web applications on top of the Java EE platform. The framework does not impose any specific programming model.. The framework has become popular in the Java community as an addition to the Enterprise JavaBeans (EJB) model. The Spring Framework is free and open source software.

The Java API for XML Messaging (JAXM) enables distributed software applications to communicate using XML (and SOAP). JAXM supports both asynchronous and synchronous messaging.

The Jakarta Expression Language is a special purpose programming language mostly used in Jakarta EE web applications for embedding and evaluating expressions in web pages. The specification writers and expert groups of the Java EE web-tier technologies have worked on a unified expression language which was first included in the JSP 2.1 specification (JSR-245), and later specified by itself in JSR-341, part of Java EE 7.

Java view technologies and frameworks are web-based software libraries that provide the user interface, or "view-layer", of Java web applications. Such application frameworks are used for defining web pages and handling the HTTP requests (clicks) generated by those web pages. As a sub-category of web frameworks, view-layer frameworks often overlap to varying degrees with web frameworks that provide other functionality for Java web applications.

Jakarta RESTful Web Services, is a Jakarta EE API specification that provides support in creating web services according to the Representational State Transfer (REST) architectural pattern. JAX-RS uses annotations, introduced in Java SE 5, to simplify the development and deployment of web service clients and endpoints.

References