Introduction to Java Servlets
In this article, I am going to give you a brief introduction to Java Servlets. Please read our previous article where we gave a brief introduction to the web and understanding the different web terminology. As part of this article, we are going to discuss the following pointers in detail.
- What is not Servlet?
- What is Servlet?
- What is the need for Servlet Technology?
- What is Web Container?
- What can a Servlet do in a java website?
- What are the similarities between Static and Dynamic Webpages?
- What are the Differences between Static and Dynamic Webpages?
- What is Java Servlet?
- What is a Servlet Container?
- Advantages of Servlet
- Features of Servlet
- Difference Between Servlets and JSP
- Why learn servlet?
- Applications of Servlet
- Java Servlets Architecture
- Servlet Packages
What is not Servlet?
- Servlet is not a programming language unlike java(J2SE).
- Servlet is not software to be installed into a computer system.
What is Servlet?
Servlets is a java-based web technology from Sun Microsystems. Servlet technology is J2EE technology.
What is the need for Servlet Technology?
- Servlet technology is used in the development of web-enabled Java enterprise applications. OR
- Servlet technology is used to develop java based dynamic websites. OR
- In java-based web application development, servlet technology is used.
What is Web Container?
A web container is server software that consists of three modules
- Web server (HTTP server)
- Servlet container (Servlet engine)
- JSP container (JSP engine)
For example, Tomcat from ASF (Apache Software Foundation).
Servlet container is a special software module written in java language according to java specification. Servlet container executes user-defined servlets of the java web application.
JSP container is a special software written in java language according to java specification. JSP engine executes user-defined JSPs of the java web application.
Without user-defined servlets and JSPs, the website can’t become Dynamic. The web server can’t execute servlets and JSPs. Therefore, a java-based web application web server is insufficient and the web container is required.
What is a Servlet?
A servlet is a user-defined public java Class that implements javax.servlet.Servlet interface and it is managed by the servlet container.
- A servlet is a Dynamic Web Resource that enhances the functionality of the webserver.
- A servlet is a Web Server-Side Piece of Code (server-side program).
- A servlet is a Web Component.
Note: A web application has static and dynamic web resources. The presence of dynamic web resources makes that website dynamic (interactive). Example of static resources: HTML document and image files. Example of dynamic web resources: servlets and jsps
What can a Servlet do in a java website?
To make the website interactive, a servlet can do the following tasks being a web server-side piece of java code (server-side program).
- Capturing user input.
- Communicating with the database.
- Processing of the data.
- Producing the response page.
- Handing over the response page to the webserver.
What are the similarities between Static and Dynamic Webpages?
- Both are developed by using Hypertext Markup Language (HTML) only.
- Both are sent by the webserver to the web client only.
- Both are executed and rendered (display) by web client (browser) only.
What are the Differences between Static and Dynamic Webpages?
We have to consider the following four things.
- When is that page created?
- Is it stored in the hard disk (file) of the web server machine?
- Is their content change with user interaction?
- Whether a server-side program creates it or not.
So, the following are the differences between Static and Dynamic Web Pages.
What is Java Servlet?
Servlet is the server-side technology designed on the idea of java technology. Java technology may be a Thread based technology; it’ll make servlets as Thread based technologies. If we deploy any servlet application at the server then for each client request servlet container will generate a separate thread on the respective servlet object. If we increase the number of requests even containers will create a number of threads instead of processes.
When compared to process thread is lightweight, to handle multiple numbers of requests i.e. thread server machine may not get burden, it may provide quick responses for the client request, it may increase the performance of the server-side application.
Today servlets are the favored choice for building interactive web applications. Third-party servlet containers are available for Apache Web Server, Microsoft IIS, etc. Servlet containers are usually the components of web and application servers, like BEA WebLogic Application Server, IBM WebSphere, Sun Java System Web Server, Sun Java System Application Server, and others.
Servlets are not designed for a specific protocol. It is different things that they’re most ordinarily used with the HTTP protocols. It is different things that they’re most ordinarily used with the HTTP protocols. Servlets use the classes within the java packages javax.servlet and javax.servlet.http. Servlets provide a way of creating the sophisticated server-side extensions in a server as they follow the standard framework and use the highly portable Java language.
CGI(Common Gateway Interface)
The Common Gateway Interface, which is normally referred to as CGI, was one of the practical techniques developed for creating dynamic content. By using the CGI, an internet server passes requests to an external program and after executing the program the content is shipped to the client because of the output. In CGI when a server receives an invitation it creates a replacement process to run the CGI program, so creating a process for every request requires significant server resources and time, which limits the number of requests that can be processed concurrently. CGI applications are platform dependent. There is no doubt that CGI played a major role in the explosion of the Internet but its performance, scalability issues make it less than optimal solutions.
Disadvantages of CGI
- It does not interact with the User directly.
- It does not interact with a web browser or a graphical interface directly.
- It does not create windows by itself.
- It does not display or retrieve information from menus, commands, and other interactive features of a client browser.
What is a Servlet Container?
A servlet container is a compiled, executable program. The main function of the container is to load, initialize, and execute servlets. The servlet container is the official Reference Implementation for the Java Servlet and Java Server Pages technologies. The Java Servlet and Java Server Pages specifications are developed by Sun under the Java Community Process.
A container handles a sizable number of requests because it can hold many active servlets, listeners, etc. It is interesting to notice here that the container and therefore the objects during a container are multithreaded. So, each object must be thread-safe during a container because the multiple requests are being handled by the container thanks to the doorway of quite one thread to an object at a time.
Note: A Servlet Container may run standalone i.e. without an internet server or maybe on another host.
Advantages of Java Servlet
- Portability: Servlets are highly portable across operating systems and server implementations because servers are written in java and follow well known standardized APIs so they are.
- Powerful: It is possible to do several things with the servlets which were difficult or even impossible to do with CGI.
- Efficiency: As compared to CGI the invocation of the servlet is highly efficient. When the servlet gets loaded in the server, it remains in the server’s memory as a single object instance.
- Safety: As servlets are written in java, servlets inherit the strong type safety of java language. Servlets are generally safe from memory management problems because of Java’s automatic garbage collection and a lack of pointers.
- Integration: Servlets are tightly integrated with the server. Servlet basically uses the server to translate the file paths, perform logging, check authorization, and MIME type mapping, etc.
- Extensibility: The servlet API is designed in such a way that it can be easily extensible. As it stands today, the servlet API supports HTTP Servlets, but later it can be extended for another type of servlets.
- Inexpensive: There are numbers of free web servers available for personal use or for commercial purposes. Web servers are relatively expensive. So, by using the available web servers you can add servlet support to it.
Features of Servlet
- Dependency on J2SE: The minimum platform requirement for Servlet is JDK 1.5. The Servlet can’t be used in versions less than JDK 1.5.
- Support for annotations: Annotations provide a mechanism for decorating java code constructs with metadata information. Annotations are mark code in such a way that code processors may alter their behavior based on the metadata information.
- Several web.xml conveniences: Servlet introduces several small changes to the web.xml file to make it more convenient to use. For example, while writing a <filter-mapping>, we can now use an asterisk in a <servlet-name> which will represent all servlets as well as JSP.
Previously we used to do
<filter-mapping> <filter-name>FilterName</filter-name> <servlet-name>FilterName</servlet-name> </filter-mapping>
<filter-mapping> <filter-name>FilterName</filter-name> <servlet-name>*</servlet-name> </filter-mapping>
Previously in <servlet-mapping> or <filter-mapping> there used to be only one <url-patterrn>, like
<servlet-mapping> <servlet-name>abc</servlet-name> <url-pattern>/abc/*</url-pattern> <url-pattern>/abc/*</url-pattern> </servlet-mapping>
There are many more facilities added in web.xml apart from these changes.
- A Handful of removed restrictions: Servlet removed a few restrictions around error handling and session tracking. Now it has removed the restrictions that the <error-page> could not call the setStatus() method to alter the error code that triggered them. In session tracking, Servlet eased a rule that a servlet called by RequestDispatcher include() couldn’t set response headers.
- Some edge case clarifications: The servlet specification says that before calling request.getReader() we must call request.setCharacterEncoding().
Difference Between Servlets and JSP
Use of Servlet
- Receives client request in the form of the HTTP request
- Extract some information from the request received
- Do content generation or business logic processes by accessing the database, invoking EJBs, etc
- Create and send a response to the client in the form of an HTTP response or forward the request to another servlet or JSP page.
Why learn servlet?
The primary purpose of Servlet specification is to define a strong mechanism for sending content to a client as defined by the Client/Server model. Servlets are most popularly used for generating dynamic content on the online and have native support for HTTP. A servlet is a Java programing language class that wants to extend the capabilities of servers that host applications accessed by means of a request-response programming model. Although servlets can answer any sort of request, they’re commonly wont to extend the appliance hosted by web servers. Java Servlet technology defines HTTP specific servlet classes for such applications.
Applications of Servlet
- It helps reads the explicit data sent by the clients. It includes an HTML form on a Web page.
- It reads the implicit HTTP request data sent by the clients (browsers). This includes cookies, media types, and compression schemes that the browser understands.
- It processes the data and generates the results. This process includes talking to a database, invoking a Web service, or computing the response directly.
- It sends explicit data to the clients. This document can be sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc.
- It sends the implicit HTTP response to the clients. This includes telling the browsers or other client’s what type of document is being returned, and other such tasks.
Java Servlets Architecture
The lifecycle of a Servlet is controlled by the web container in which the servlet has been deployed.
First, the Client browser sends an HTTP Request to the webserver. Then, the Web server forwards requests to Web Container. Web Container then forwards it to the Servlet in form of the request object. Then Servlet generates a response object and sends it to the Web Container. Web container again converts it into an equivalent HTTP response to the webserver. The web server, at last, sends HTML content via HTTP response back to the client browser.
Servlets are created using the javax.servlet and javax.servlet.http packages. These packages are a standard part of the Java’s enterprise edition and an expanded version of the Java class library that supports large-scale development projects.
javax.servlet.*: It contains a number of classes and interfaces. It describes and defines the contracts between a servlet class and the runtime environment.
javax.servlet.HTTP.*: It contains a number of classes and interfaces. It describes and defines the contracts between a servlet class running under the HTTP protocol and the runtime environment.
In the next article, I am going to discuss HTTP Protocols in detail. Here, in this article, I try to give a brief introduction to Java Servlets. I hope you enjoy this Java Servlets article.
About the Author: Pranaya Rout
Pranaya Rout has published more than 3,000 articles in his 11-year career. Pranaya Rout has very good experience with Microsoft Technologies, Including C#, VB, ASP.NET MVC, ASP.NET Web API, EF, EF Core, ADO.NET, LINQ, SQL Server, MYSQL, Oracle, ASP.NET Core, Cloud Computing, Microservices, Design Patterns and still learning new technologies.