Introduction to Java Servlets

This tutorial is a summary of Java servlet technologies. It is intended for learners who want to learn the most important concepts quickly. The rest you can find in the official tutorial of Java EE 6.

Why do we use servlets

Servlets are used to create a web application and to implement Java classes that respond to user requests. They can communicate over any client-server protocol, but they are sometimes used with the HTTP protocol. A web developer can use a servlet to add dynamic content to the web server using the Java platform. The generated content is an HTML code, but can also be another code such as XML. Multiple servlets make up a web application.

What is a Servlet

Java servlets are a part of Java Enterprise Edition (Java EE). This was the first technology for Java and many other web technologies had arrived since then.

Java Servlets is a program that inherits server capabilities and can respond to any type of queries. However, servlets implement applications on web servers. Servlets in Java are equivalent to technologies like PHP and ASP.NET.

To use and run a servlet, you need to run your applications on a web server and a web container (servlet container or web container). The web container is responsible for managing the lifecycles of the servlets. Here's an illustration:


Java servlet inside a web container

The servlet API is in the package javax.servlet. This package  Defines the interaction between a servlet and the web container. The servlet object receives a query  and  generates  An answer based on this  query

Servlets can  being  Automatically generated from JavaServer Page  (JSP) by the JavaServer Page compiler. The difference between servlets and JSPs is that servlets are embedded in Java code, while JSPs are embedded in HTML.

A servlet container can run multiple web applications by: same  time, each has multiple servlet that are running at  Inside. Here is   an illustration:

Java web application and multiple servlet inside a web container

Query  and HTTP

The browser sends a  query  HTTP to the Java web server. The web server checks if this query  is  for  a servlet. If this is the case, the web container will find the servlet related to that request and activate it by calling the Servlet.service().

Once the servlet is enabled via the service(), it deals with the query  and generates a response that is  returned to browser.

Some Servlet Containers

As described, servlets are typically run at  The Interior  a Java web server. Web Servers Free Java are:
  • Tomcat: is an open source web container from the Apache.
  • Jetty: open source from the Eclipse Foundation.
  • GlassFish: open source from the Oracle Foundation.