General
10 May 2012 2 Comments

An Introduction To Java Web Applications

Introduction

A Web application is an application that is accessed over a network such as the Internet or an intranet. While the earliest websites served only static web pages, dynamic response generation quickly became possible via CGI scripts, JSPs (JavaServer Pages), servlets, ASPs (Active Server Pages), server-side JavaScripts, PHP, or some other server-side technology.

Java has become a popular language for creating dynamic Web applications over the last 15 years, due to the introduction of servlets, JSP, and frameworks such as JSF and Spring. In this post we give an overview of these technologies, and explain the the major differences between them.

Building Blocks

For the sake of simplicity we distinguish three types of Web application building blocks: servlets, JSPs and frameworks

Servlets

In Java, Web applications consist of servlets. A servlet is a small Java program that runs within a Web server. Servlets receive and respond to requests from Web clients, usually across HTTP. An example of a servlet that takes a request and returns a page with the numbers 1 to 10 is given below.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
 
public class HelloWorldServlet extends HttpServlet
{
  public void doGet (HttpServletRequest req,
                     HttpServletResponse res)
    throws ServletException, IOException
  {
    PrintWriter out = res.getWriter();
    out.println("");
    out.println("Greeting Page");
    out.println("The numbers are:
    "
); for (int i=1; i<=10; i++) { out.println("
  • "
  • + i + ""); } out.println(""); out.println(""); out.close(); } }

    JSP

    Developing a Web application in plain servlets was a pain: imagine the horror of having hundreds of println() calls with HTML tags or Javascript code spread out over all your classes. This problem was alleviated in 1999 with the release of JavaServer Pages (JSP). With JSP you could write HTML in a JSP file, and the server would automatically create a servlet from the page. JSP also allows you to write blocks of Java code inside the JSP.

    An example of a simple JSP page that prints a bullet list with the numbers 1 to 10 is given below.

    <html>
    <body>
    The numbers are:
    <ul>
    <%
        for (int i=1; i<=10; i++) {
            %>
            <li><%= i %>li>
            <%
        }
    %>
    ul>
    body>
    html>

    Unfortunately, having Java inside HTML proved almost as awkward as having HTML inside Java. It could easily create a hard to read mess. It was only years later when the introduction of JSTL and EL alleviated this problem somewhat by providing tags and expressions that could be used in JSP’s, instead of Java code.

    Web Frameworks

    Even with the improvements to JSP, developing with “plain vanilla” JSP/servlets can be quite laborious: you’ll have to bring in a lot of code to control, preprocess, postprocess, gather data, validate, convert, listen, etc the HTTP request and response. The shortcomings of plain servlets and JSP sparked the creation of many Web frameworks that intended to make Web application development easier. These frameworks are built on top of JSP/servlet technology: most frameworks use JSP in some shape or form, and all frameworks eventually create servlets.

    A key selling point of most frameworks is the separation between the presentation of a page and the underlying logic. This means there is no intermingling of HTML and Java! In addition, many frameworks provide libraries for database access, templating frameworks and session management, and they often promote code reuse. A timeline with the release dates of some well-known Web frameworks is displayed below 1.

    A timeline with the release dates of some Web frameworks. Most of them are Java frameworks, but some other ones are included.

    Over the last 10 years plain servlets and JSP have gradually been replaced by Web frameworks as the technology of choice. In 2012, using frameworks has become the standard; using JSP is only an option for very small Web applications. For larger projects frameworks are a must, since they remove the need to reinvent the wheel over and over during implementation.

    The interesting parts of a Hello World application for the JSF 2.0 framework look something like this:

    Hello.java

    package hello;
     
    import javax.faces.bean.ManagedBean;
     
    @ManagedBean
    public class Hello {
     
        final String world = "Hello World!";
     
        public String getworld() {
            return world;
        }
    }

    hello.jsf

    <html lang="en"
          xmlns="http://www.w3.org/1999/xhtml"
          xmlns:h="http://java.sun.com/jsf/html">
        <h:head>
            <title>Facelets Hello Worldtitle>
        h:head>
        <h:body>
            #{hello.world}
        h:body>
    html>

    Which Technology Should I Use?

    That’s a good question. As with all things software, there is no unified answer (another ten posts could be dedicated to trying to give a complete answer). Servlets and JSPs are lightweight, but there are other lightweight technologies to consider, e.g. PHP. Frameworks are more powerful, but if you are building a very small Web application using a full-blown framework may be overkill. It all depends on your demands and personal preference.

    If you are considering a framework, you have to choose between an uncountable number of web-frameworks that exists in the Java environment. The bottom line is that most frameworks will do the job, and you can’t really judge a framework until you have actually tried it. Here are some links to get you started.

    An overview of which Java EE standards are used the most (source: ZeroTurnaround).

    What is Java EE?

    In many documents about Java Web applications you will run into the term Java EE, but what does it mean exactly?

    The short answer is that Java EE refers to Java Platform Enterprise Edition. The long answer is, well, longer.

    Language vs Platform

    Java technology is both a programming language and a platform. The Java programming language is a high-level object-oriented language that has a particular syntax and style. A Java platform is a particular environment in which Java programming language applications run. Every platform has an API that defines things like the classes that are available to the programmer, and which functions are available in each class.

    When most people think of the Java programming language, they think of the Java SE API. Java SE’s API provides the core functionality of the Java programming language. It defines everything from the basic types and objects of the Java programming language to high-level classes that are used for networking, security, database access, graphical user interface (GUI) development, and XML parsing.

    So, the Java language defines that you can use an if statement, and that single line comments start with //:

    if (x == y)
    {
      // A comment
    }

    And the Java SE API defines the existence of the List, ArrayList and String objects:

    List<String> = new ArrayList<String>();

    The platform APIs are just APIsimplementation of classes defined in the API. There are various different implementations by other parties, e.g. the open source Java SE implementation OpenJDK.

    Java SE vs Java EE

    The editions of the Java platform range from lightweight to heavyweight. For ‘normal’ computers two versions are available: Java SE and Java EE. The image below gives an overview (source).

    An overview of Java Platform editions. The Java EE edition is the 'largest' of all java versions.

    Java Platform Enterprise Edition or Java EE is the enterprise Java computing platform. The platform was known as Java 2 Platform, Enterprise Edition or J2EE until the name was changed to Java EE in version 5. The current version is called Java EE 6. Java EE extends Java SE, providing an API for fault-tolerance, object-relational mapping, distributed and multi-tier architectures, and web services.

    Some of the top-level packages (there are 11 in total) defined by the Java EE API are:

    javax.faces.*          This package defines the root of the JavaServer Faces (JSF) API.
    javax.servlet.*        The servlet specification defines a set of APIs to service mainly HTTP requests. It includes the JavaServer Pages specification.
    javax.ejb.*            The Enterprise JavaBean (EJB) specification defines a set of lightweight APIs that an object container (the EJB container) will support in order to provide transactions (using JTA), remote procedure calls (using RMI or RMI-IIOP), concurrency control, dependency injection and access control for business objects.
    javax.persistence.*    This package contains the classes and interfaces that define the contracts between a persistence provider and the managed classes and the clients of the Java Persistence API (JPA).

    The reference implementation of the Java EE platform is called Glassfish. This implements the new packages defined by Java EE. There are several other implementations that provide a runtime environment for Java EE programs, such as JBoss and WebSphere. Since Java EE runs ‘on top’ of Java SE, Java EE programs can use all features of Java SE.

    Note that just because Java EE stands for Enterprise Edition, it does not mean that it is used only by enterprises. Java EE is the name given to a set of specifications that are bundled together to form a platform. The moment you need to write a web application, you need to use the Servlet + JSP specifications at a bare minimum, which are both contained in the EE specification. So you can simply do more stuff with a Java EE application because it can use the additional APIs provided by the Java EE specification.

    Java Web Application Servers

    Understanding the differences between a web server, a servlet container and an application server is important when learning how a Java Web application is presented to its end users. The servlet/application/EJB container terms are a bit ambiguous, but we will try to come to a workable definition. Let’s take a look.

    Web Server

    A Web server handles the HTTP protocol. When the Web server receives an HTTP request, it responds with an HTTP response, such as sending back an HTML page. To process a request, a Web server may respond with a static HTML page or image, send a redirect, or delegate the dynamic response generation to some other program such as CGI scripts, JSPs (JavaServer Pages), servlets, ASPs (Active Server Pages), server-side JavaScripts, or some other server-side technology. Whatever their purpose, such server-side programs generate a response, most often in HTML, for viewing in a Web browser 2. The Web server itself does not dynamically generate responses, it just handles receiving the request and sending the response.

    The most commonly used Web servers are Apache, Microsoft IIS and nginx.

    Web Container

    A Web container (or servlet container) is a program that provides an environment for the servlets and JSP to run. Putting it differently we can say that a Web container is combination of a Servlet Engine and a JSP Engine. Most Web containers also include a Web server, so they can run stand-alone.

    The Web container is responsible for managing the lifecycle of servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access rights. If an HTTP Request refers to a Web Component (typically a servlet or a JSP) then the request is forwarded to the Web Container and the result of the request is sent back to Web Server, which uses that result to prepare the HTTP Response for the particular HTTP Request.

    So a Web container provides a runtime environment for a subset of the Java EE specification, usually only the JSP and Servlet parts. This means a programmer could write the following:

    import javax.servlet.*;
    import javax.servlet.http.*;

    This would work just fine, because the Web container contains an implementation of javax.servlet.*. The use of JSP is also allowed, e.g. using tags.

    <jsp:include page="hello.jsp"/>

    But you can’t use other Java EE features such as Enterprise Java Beans (EJBs):

    import java.util.Collection;
    import javax.ejb.Remote;
     
    @Remote
    public interface Cart {
        public void addItem(String item);
        public void removeItem(String item);
        public Collection getItems();
    }

    This will not work because the Web container does not know the javax.ejb.* package. When you do need EJBs it may be possible to extend a Web container with additional Java EE implementation parts, but it is a much better idea to use a full-fledged Java EE application server.

    The most common Web container are Tomcat and Jetty. Tomcat 7 implements two specifications: JSP 2.2 and Servlet 3.0.

    Application Server

    An application server (a.ka. Java EE server or application container) is a server that provides support for the entire Java EE specification. It can run applications that use EJBs, provides transaction support through the javax.transaction.* package, etc. In addition it provides the capabilities of a Web Container as well as of a Web Server. The image below shows a full application server (source).

    An application server provides support for the full Java EE specification.

    In an application server, programs can happily use the full Java EE specification, e.g. declaring Entity Beans:

    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue; 
    import javax.persistence.Id;
    import javax.persistence.Table;
     
    @Entity  
    @Table(name="bookbank")
    public class Book implements Serializable 
    {   
      @Id 
      Long empid;
     
      @GeneratedValue 
      public Long getId() 
       { return id; }  
        public void setId(Long id)  
      { this.id = id; }  
    }

    How Is a Java Web Application Distributed?

    As we just learned Java Web applications are run in Web containers or application servers. But how do you present a Web application to the server? The short answer is this:

    Web applications are packaged in WAR and EAR files. Web containers (e.g. Tomcat) accept WAR files. Application servers (e.g. Glassfish) accept WAR files and EAR files.

    For a more detailed explanation we have to dig deeper…

    A Java EE application is delivered in a Java Archive (JAR) file, a Web Archive (WAR) file, or an Enterprise Archive (EAR) file. A WAR or EAR file is a standard JAR file with a .war or .ear extension. Using JAR, WAR, and EAR files and modules makes it possible to assemble a number of different Java EE applications using some of the same components4. Note that a Java Web application is always a Java EE application, but the opposite is not true. Only Java EE applications packages in WAR and EAR files are web applications.

    JAR: Java ARchive

    A JAR (Java ARchive) is an archive file format typically used to aggregate many Java class files and associated metadata and resources (text, images and so on) into one file to distribute application software or libraries on the Java platform.

    • Based on the ZIP format: it can aggregate many files and directories into one aggregate file, possibly compressing them.
    • A manifest file is a specific file contained within a JAR archive. It is used to define information about the JAR.
    • The manifest file is named MANIFEST.MF and must be located at META-INF/MANIFEST.MF in the JAR.
    • One of the most common uses of JAR files is to bundle all the .class files, and other required component files of a library into a JAR file and include that JAR file into the CLASSPATH of another Java application which requires the services of that library.
    • EJB modules contain class files for enterprise beans and an EJB deployment descriptor. EJB modules are packaged as JAR files with a .jar extension.
    • Application client modules, which contain class files and an application client deployment descriptor. Application client modules are packaged as JAR files with a .jar extension.

    WAR: Web application ARchive

    A WAR file (or Web application ARchive) is a JAR file used to distribute a collection of JavaServer Pages, Java Servlets, Java classes, XML files, tag libraries and static Web pages (HTML and related files) that together constitute a Web module.

    • A WAR file contains what is known as a web module. It is the smallest deployable and usable unit of web resources.
    • Web containers (Tomcat) and application servers (Glassfish) can both
    • The top-level directory of a web module is the document root of the application. The document root is where JSP pages, client-side classes and archives, and static web resources, such as images, are stored.
    • The document root contains a subdirectory named WEB-INF, which can contain the following files and directories:
      • classes: A directory that contains server-side classes: servlets, enterprise bean class files, utility classes, and JavaBeans components
      • tags: A directory that contains tag files, which are implementations of tag libraries
      • lib: A directory that contains JAR files that contain enterprise beans, and JAR archives of libraries called by server-side classes
      • Deployment descriptors, such as web.xml (the web application deployment descriptor) and ejb-jar.xml (an EJB deployment descriptor)

    The structure of a WAR file looks like this:

    The structure of a WAR file4.

    Most real Web applications will use a web.xml file. It instructs the servlet container (e.g. Tomcat) on how to deploy and run the Web application. An example web.xml file is:

      version="1.0" encoding="UTF-8"?>
     
         PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
         "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
     
     >
         >
             >HelloServlet>
             >mypackage.HelloServlet>
         >
     
         >
             >HelloServlet>
             >/HelloServlet>
         >
     
         >
             >
                 Resource reference to a factory for javax.mail.Session
                 instances that may be used for sending electronic mail messages,
                 preconfigured to connect to the appropriate SMTP server.
             >
             >mail/Session>
             >javax.mail.Session>
             >Container>
         >
     >

    EAR: Enterprise ARchive

    An EAR (Enterprise ARchive) file contains Java EE modules and, optionally, deployment descriptors. When a large Web application is deployed, all its .jar and .war files are packaged as JAR file with .ear extension and deployed into an application server.

    • In addition to Web modules (WAR files), an EAR file can contain EJB modules (JAR), Application client modules (JAR) and Resource adapter modules (RAR).
    • Deploying EAR files requires an application server such as Glassfish.
    • Web containers such as Tomcat can not deploy EAR files, only WAR files.

    EAR file structure5.

    Sources

    1. App server, Web server: What’s the difference?
    2. Java EE Containers – The Java EE 5 Tutorial
    3. Web Modules – The Java EE 6 Tutorial
    4. Packaging Applications – The Java EE 6 Tutorial
    Tags: ear, enterprise edition, framework, , jar, , , , jsp, servlet, standard edition, tomcat,

    2 Responses to “An Introduction To Java Web Applications”