Web application with Java Servlets

One of the most enjoyable features of Java is its multifaceted nature. Of course, creating traditional desktop and even mobile applications is great. But what if you want to get off the beaten track and enter the territory of web application development in Java? There is good news for you: the language comes with a full-fledged Servlet API, which allows you to create reliable web applications without much hassle.

This article is for sequels. If you are just starting to get acquainted with Java, we advise you to take a quick start, watch a video course and choose one of the books for beginners.

Creating Java applications using Servlets

Meet servlets, a special type of Java program that runs within a web container (also called a servlet container, such as Tomcat and Jelly), that allow you to process client requests and server responses easily and efficiently. Now is not the time or place to meticulously explain to you what a servlet is. Suffice it to say that servlets are created and destroyed by their containers, not the developer, and act as an intermediate layer between clients (usually web browsers) and other applications running on the server (such as databases).

Servlet is a cool thing that can, among other things, receive data from the client, usually through GET and POST requests, work with cookies and session parameters. And it processes data through additional levels of applications and sends the output to the client in both text and binary formats (HTML, XML, PDF, JPG, GIF, etc.), in many cases using Java Server Pages (JSP) files.

It is best to start working with servlets through a specific example. We will create a simple web application that will allow customers to register using a simple HTML form. The data provided by customers will be collected with a servlet and checked by validators.

The first step to building an application is to define a so-called deployment descriptor. It specifies how the application should be deployed in a specific environment. When it comes to web applications, the deployment descriptor is a simple XML file called web.xml and is part of the standard Java EE specification. In our case, it will look like this:

As you can see, web.xml only defines the version of the Java Servlet Specification (3.1) that we will use in the application. Of course, it can contain much more content, including servlet mapping directives, initialization settings, a list of welcome files, and a few additional settings. But in order not to complicate the development process, let’s leave it as it is.