Monday, October 10, 2016

Building a Web App with Java Servlets

One of nicest features of Java is its rich, multifaceted nature. Sure, building traditional desktop and even mobile applications is all well and fine. But what if you want to leave your current background behind and start stepping on the web terrain? The good news is that the language ships with the fully-fledged Servlet API, which lets you build robust web applications without much hassle.

The question that must be spinning in your mind now is “How?”, am I right?

A Quick and Dirty Introduction to Java Servlets

Enter servlets, a specific type of Java program executed within the scope of a web container (also called servlet containers, Tomcat and Jetty are prime examples), which allows to handle client requests and server responses in a straightforward and performant fashion. This isn’t the place and time for boring you to tears with academic definitions on what a servlet is. Suffice it to say that servlets are instantiated and destroyed by their containers instead of the developer and act as a middle layer between clients (usually web browsers) and other applications running on the server (databases, for example).

Servlets are powerful creatures, which, among other nifty things, can grab data from the client, typically through GET and POST requests, handle cookies and session parameters, process the data via additional application layers, and send the output back to the client in both text and binary formats (HTML, XML, PDF, JPG, GIF, and so on), in many cases by using a Java Server Pages (JSP) file.

The best way to get started using servlets is with a concrete example. Thus, in the next few lines I’m going to build up a simple web application that will let customers sign up using a plain HTML form. Data submitted by customers will be collected by a servlet and validated at a very basic level through some static helpers.

Consuming the HTTP Client-Server Model

To have a clear idea on how the customer application will be structured, here’s how it will be laid out:

java_servlet_application_layout

Nothing unexpected, right? But first things first.

The first step we need to take to build the application is to define the so-called deployment descriptor (DD). As the name suggests, it specifies how an application should be deployed in a specific environment. Not surprisingly when it comes to web applications, the deployment descriptor is a plain XML file called web.xml and is part of the standard Java EE specification. In this particular case, it’ll look like this:

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="3.1"
             xmlns="http://ift.tt/19L2NlC"
             xmlns:xsi="http://ift.tt/ra1lAU"
             xsi:schemaLocation="http://ift.tt/19L2NlC http://ift.tt/1drxgYl"
             metadata-complete="false">

</web-app>

As shown above, the web.xml file contains no directives at all and only defines the version of the Java Servlet Specification (3.1) that we’ll be using across the application. It can of course hold a lot more content, including servlet mapping directives, intialization parameters, a list of welcome files and a few additional settings. But to keep the whole development process easy to follow, I’ll keep the file that simple.

Since the sample application will consume the Servlet API and also use Java Server Pages for displaying customer data, we need to grab all the required JARs. Maven will do the tough work for us, so here’s how the POM file will be defined:

<project xmlns="http://ift.tt/IH78KX" xmlns:xsi="http://ift.tt/ra1lAU"
             xsi:schemaLocation="http://ift.tt/IH78KX http://ift.tt/HBk9RF">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.electricalweb.customerapplication</groupId>
    <artifactId>customerapplication</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>Customer Application</name>
    <url>http://ift.tt/1xLIsqm;

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>

        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>el-api</artifactId>
            <version>2.2</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>Customer Application</finalName>
    </build>
</project>

In a nutshell, the pom.xml file defines all the dependencies required for working with servlets: JSP, the Java Standard Tag Library (JSTL), and the Java Expression Language (JEL).

At this point, we've managed to create the customer app configuration files. However, in its current state the application literally does nothing. Yikes! Since the primary goal here is to let customers sign up using an HTML form, the next thing we need to do is to define the JSP files tasked with rendering the aforementioned form and with displaying customer data once the signup process has been successfully completed. That’s exactly the topic covered in the next section.

Creating the Sign-up and Welcome Views

The presentation layer will be made up of two JSP files - in an MVC context, these are called views. The first one will be responsible for rendering the signup form and for displaying eventual errors triggered after validating the inputted data. The second one will be a typical welcome page, which will show the data submitted by the customer after successfully completing the signup process.

Continue reading %Building a Web App with Java Servlets%


by Alejandro Gervasio via SitePoint

No comments:

Post a Comment