Oprah Winfrey said, "I'm black, I don't feel burdened by it, and I don't think it's a huge responsibility. It's part of who I am. It does not define me."
Java Servlet is perhaps one of the oldest application programming interfaces for running Java on a web application server. It is the conceptual mirror of the original Java Applet, the sandbox environment that allowed byte codes to be run in a JVM, embedded into a web browser. Java Servlet is a remote endpoint for an HTTP communication also, in a sort of sandbox environment, but now we call it a web container.
From Java Servlets, in the late 1990's, there came a flurry of technologies to do with the World Wide Web and the exponential growth of the Internet, which saw the ushering of the contemporary digital age in fast communication. Java Servlets expanded and were supported by Java Server Pages (JSP), Java Server Page Tag Libraries (JSTL), and then Java Server Faces (JSF).
Java Servlets are the foundation of understanding how Java works in a web environment using the Java EE 7 specification and the Standard. Although the humble Servlet is not the only way to generate dynamic web content for today's digital media, social networking, and cloud computing requirements for a scalable and sustainable business, it is so well known by the Enterprise Java professionals, it is worth your while getting to know how it operates.
In this chapter, we will cover only the essential features of the traditional Java Servlet model. There are lots of tutorials, online descriptions, and, of course, books that describe how Java Servlets handle the requests and responses in a synchronous fashion. The aim of the chapter is to review the new features of Java Servlet 3.1 including the improvements in the API to handle asynchronous input and output. But first, let us understand exactly what Java Servlets are. Why do we need them and how do we use them?
A Java Servlet is a web component managed container. Java Servlets are based on the Java technology, they generate dynamic content, and hence the container that manages them is capable of delivering dynamic content to the web client. Because Java Servlets are built, most of the time, in the Java language, they are executed in a Java Virtual Machine (JVM), and the container that manages them controls their entire lifecycle and is responsible for starting and stopping them. Servlets interact with the world through a protocol called request-response.
A web client sends a request to the container that dispatches the request to a specific Java Servlet, which in turn processes the request, and then generates a response. The web client receives the response of the Servlet and can take further action accordingly.
In the business, we normally call these containers web containers, because they not only manage the dynamic content components, such as Java Servlets, but also JSP and JSF, and deliver static content, such as HTML, images, and other MIME content.
Web containers communicate with the outside world, the web client with the HTTP and HTTPS protocols. These specifications are the foundation of the World Wide Web, and allow the Java components to communicate over the Internet's hypermedia platform. The standard and certified web containers for Java all implement HTTP/1.1, which are the HTTP protocols, governed by the Request For Comments (RFC) standards, namely RFC 2619 (June 1999), which defines the standard.
The Java Servlets specification talks about the container as a Servlet container. For the most part, this is an artifact of history of the Enterprise platform; Servlets were one of the earliest Java Enterprise Editions standards to be delivered along with Enterprise Java beans. For all intents and purposes, the Servlet containers are practically web containers in the open source and business worlds. There was a time in the beginning, in the first implementations of Enterprise Java, where only Servlets existed. There was no JSP or JSF, and hence the name, Servlet container, stuck around and continues to this day.
A web container can be a separate entity of a web server, as Apache Tomcat is separate to the Apache HTTP Server. A web container can also be part of a full application server, such as the GlassFish server. A web browser client communicates with the web applications inside a web container using the Java Servlet API, which is the standard library for the HTTP communications.
The Servlet container (or web container) manages the lifecycle of the web applications, which are deployed to it (or undeployed from it). Each web application is separated from the other, because they are associated with their own ClassLoader
, so effectively no instances of the class context are visible to any of the parallel contexts. All web applications in the container will share the boot classpath and the web container's common ClassLoader
. Each web application has a combination of Java Servlet, filter, context listeners, and dynamic content, JSP or JSF. Many traditional business applications employed a web framework in order to add the robust application architecture, and to avoid dealing with the low-level Java Servlet API.
Java Servlets are governed by a web container (a Servlet container). The specification describes a full lifecycle of events for a Servlet. In particular, web container is responsible for loading and instantiating Servlets. The container then dispatches the requests to Servlets. Finally, when web container shuts down, it will give a chance to Servlets to close down appropriately. This is the basic model of operation.
Web container has one other important responsibility. It can host different web applications all at the same time in order to share the web server or the application server. The container must protect the web applications from interfering with each other. Therefore, Java Servlets in one web application are limited from deliberately and directly invoking, through a Java invocation, another Servlet in another web application, shared inside the same web container. It is an early form of multi-tenancy in the Java EE specification.
The package name for Servlets is called javax.servlet
, and for the HTTP Servlets it is javax.servlet.http
.
Java Servlets are defined by interface, namely javax.servlet.Servlet
, which defines the methods that all Servlets must implement.
Java Servlets are loaded when a web application is started. The Standard defines the loading time as a choice between when the web container starts or is delayed until the container determines the Servlet is needed to service a request. In other words, it is a choice for the web container implementers to make. Developer does not have any say in exactly how a Java Servlet is loaded.
For a standalone container such as Tomcat, it makes perfect sense to load the web application with its Java Servlets as soon as possible.
For a cloud computing provider, now or in the future, it may only make sense to lazily load the web application and only deliver those system resources as the circumstance-permitting may be.
The web container initiates Servlet before it can start servicing the requests from the HTTP clients. After loading a Java Servlet, the container makes a call to the init()
method. The initialization call allows a Java Servlet to acquire generic resources from other Enterprise components such as Java data persistence providers, transaction services, and other resources. The initialization call only happens once per Servlet, and the init()
method must complete successfully in order for Servlet to participate in further requests.
Web container also supplies the init()
method with a javax.servlet.ServletConfig
object. In this way, a system specific configuration can be passed to Servlet at the initialization time. Servlet can read the initialization parameters as the name and value parameters, and act upon them. A collection of the initialization parameters could be the details to connect to a database, for example the hostname, port, user credentials, and database schema name.
Web container dispatches the incoming requests to a particular web application, which it configures by the URL routing information. Once the container identifies the application, it dispatches the request to a Servlet. The container invokes the service()
method on Servlet with the following two arguments: javax.servlet.ServletRequest
and javax.servlet.Response
.
ServletRequest
contains all the information about the incoming request. In particular, it has the details of the Servlet request parameters, name and value pairs, the MIME content and length, if any, and the remote host and port of the web client.
ServletResponse
contains all the information for Servlet to generate the response. The response assists Servlet in sending back a suitable response. ServletResponse
has java.io.OutputStream
, in which a Servlet can write a dynamic response. It can also set the MIME type and length of the response with the appropriate character encoding.
It is important to understand that the Servlet model was abstracted at the very beginning to allow Servlets to serve inputs other than the HTTP requests.
Most of the time, as a developer, you would see the javax.servlet.HttpServletRequest
and javax.servlet.HttpServletResponse
objects, as it is far easier to write Servlets that inherit from the abstract base class javax.servlet.HttpServlet
.
The following table summarizes the
javax.servlet.Servlet
calls:
A Servlet can throw two types of exceptions, namely javax.servlet.UnavailableException
and javax.servlet.ServletException
.
ServletException
defines a general class of exception thrown by all the Servlet types. There is really no difference between it and the standard checked exception. It can record an error message and an optional root cause.
UnavailableException
is a subclass of ServletException
and the unavailable exception signifies that Servlet cannot be initialized or it can immediately service the incoming request. The UnavailableException
class has a method isPermanent()
that the framework can query to find out, if Servlet is permanently or temporarily disabled.
For the permanent situation, web container removes the Servlet instance from the in-active-service collection. For the temporary situation, web container will remove Servlet from service for N number of seconds, which can be established from a call to getUnavailableSeconds()
. The only difference between permanent and temporary is the call to the UnavailableException
constructor.
The abstract base class javax.servlet.http.HttpServlet
is a subclass of javax.servlet.GenericServlet
, and implements the Servlet
and ServletConfig
interfaces. As mentioned before, it is far easier to write Java Servlets that extend this abstract class, because it has facilities to support the HTTP protocol.
The HttpServlet
class takes care of decoding the HTTP method, by delegating to the following methods:
Developers who subclass the HttpServlet
class rarely have to override the service()
method, because this Servlet adds additional methods that map the HTTP request into one of the preceding methods.
Servlets are deployed to a web container using a specialized form of Java Archive (JAR), it is called a Web Archive (WAR), otherwise known as a WAR file. The WAR file is a deployment of a single web application that is deployed by a web container. The WAR file contains dynamic elements, such as Java classes organized in packages. It can also contain JSP, tag libraries, third-party libraries, and also static content.
The structure of a WAR is standard in Java EE and is based on a special directory or folder name that is reserved for the metadata content called /WEB-INF
. This is similar to /META-INF
in JAR in that the directory is hidden from view; the web container does not serve any content underneath the directory. Any other folder or files other than these two are servable by the web container.
Folder or File |
Description |
---|---|
|
The root directory of the web archive and also the web application |
|
The root directory for the web application metadata that is hidden from view |
|
The web application deployment descriptor file (optional in the Java EE 7 application server and the web profile conformant container) |
|
A subdirectory reserved for the compiled Java classes in an exploded view |
|
A subdirectory reserved for the third-party libraries distributed with the web application |
|
A subdirectory specially reserved for the tag library definitions (circa J2EE 1.4) |
|
A subdirectory specially reserved for the tag library definitions |
Under the root folder, developers can organize the structure of the web application however feels right. A sample web application with some content, which is organized in a meaningful and modern way is as follows:
/index.jsp /pages/header.jsp /pages/footer.jsp /content/ /content/application.jsp /content/app/sales/ /content/app/marketing/ /content/app/humanresources/ /images/icon.png /javascript/jquery.js /javascript/modernizer.js /styles/ /styles/main.css /styles/desktop/ie9.css /styles/tablet/ios.css /styles/tablet/android.css /styles/mobile/ /WEB-INF/web.xml /WEB-INF/classes/ /WEB-INF/lib/ /WEB-INF/tags/
The root of the JAR file is the root directory for the web application. Web containers deploy a WAR file to a web context usually by the base name of the filename, which usually derives the default name of the web application. For example, given a WAR file named seaside.war
, the default web context will be named seaside
. To reach the PNG file from a locally installed web container, we might have a URL reference, such as http://localhost:8080/seaside/images/icon.png
.
To summarize the point for the WAR file, the compiled Java classes (or from any other alternative JVM programming language) are dumped in the /WEB-INF/classes
directory. The /WEB-INF/lib
directory is where all the third-party or internal JAR libraries are copied to.
The web deployment file web.xml
, which is covered later, configures Java Servlets, the Servlet filters, and listeners for your application. It is always found in the /WEB-INF
subdirectory. Finally, your web application, if it makes use of the JSP, JSF technology, may require the tag libraries and/or define its own custom set of tag libraries and fragments for rendering the definitions of extra tag libraries. lives in the folder /WEB-INF/tags
.
Finally, your application can place static resources and dynamic pages in structure that makes sense to your organization and, of course, to your architecture.
A WAR file is a Zip file of all of the entire web applications with metadata. Deployment to web container is usually performed through a build system, such as Apache Ant, Maven, or Gradle. Some web containers provide specialist tools to deploy the WAR files, which can be standalone plugin programs for IDE, or be operated through the administration web pages inside an application server.
18.223.196.146