Java EE5 & Servlets
In this lesson we learn about the Java EE5 Platform and how servlets fit into the architecture. We already downloaded the Java EE5 version of java in the Getting The Java Software Development Kit (JDK) section but this is the standard edition of Java. Servlets and JSPs are not part of the standard edition but instead are part of what is known as the Java Enterprise Edition or Java EE5.
So what exactly is the Java EE5 version and why do we need it? Java EE5 is designed for servers and networking and as such allows the running of distributed applications between JVMs on different servers. To make all this possible all the network protocols such as HTTP and TCP/IP are supported 'under the bonnet' without us as programmers having to worry about server side programming. In fact a fully compliant Java EE5 application server incorporates the Servlets, jsp and Enterprise JavaBeans (EJB) 3.0 specifications under the same roof so we don't have to worry about inconsistencies.
EJBs handle back-end business code and are beyond the scope of these tutorials, but for the sake of the current discussion we just need to know they are housed within an EJB container. What we are interested in for these tutorials are Servlets and JSPs which are defined in the Java EE5 specification as web components. Web applications are made up of collections of web components, along with other entites of course. A web container is used to house our web applications.
The following diagram should help clarify the above points about the Java EE5 application server architecture:
In the real world a distributed application might consist of web applications, EJB applications and other applications all working together but for these tutorials we will be running our web applications in isolation. Therefore we don't need a full blown Java EE5 application server; all we need for our purposes is a web container to handle our web applications. We have already downloaded and tested our web container of choice in the section of the site.
Using A Web Container
So why use a web container for our servlets and JSPs? Well for a start servlets don't have a main() method but instead are controlled and invoked by, you guessed it, the web container. There are several other compelling reasons why using a web container makes sense, several of which are listed below:
- Communication Transparency - The container provides easy communication between the web server and any servlets held within the container, also abstracting away any programming required for these two layers to talk to each other.
- Declarative programming - The container comes with an XML Deployment Descriptor (DD) which we can configure for filtering, mapping, security and a host of other things without polluting our servlet code.
- JSP Translation - The container converts JSPs into Java so they can be run within the JVM.
- Multithreading - The container creates a new java thread every time a servlet request is received and after running the servlets service() method, the thread completes in a tidy manner.
- Servlet Lifecycle - The container controls instantiation, initialization, execution, destruction and general housekeeping of our servlets, leaving us to focus on the business logic.
Handling A Servlet Request
Now we have looked at some of the benefits a web container gives us, we will take a look at how the container receives a servlet request from a client and processes it. This should help clarify some of the roles the container performs for our servlets.
The following slideshow shows a client GET HTTP request, that points to a servlet on the server and the steps involved through to the HTTP response, showing the role of the container in this exchange. Press the button below to step through the slideshow:
In this slide our client has clicked on a link that points to a resource that is a servlet rather than a static HTML page, so the web server directs the HTTP request to our web container.
In this slide the container processes the HTTP request and creates a HttpServletRequest object and a HttpServletResponse object.
In this slide the container resolves the mapping to the servlet required via the deployment descriptor and either creates a new thread or allocates an existing thread. The container then passes the HttpServletRequest and HttpServletResponse objects to the thread.
In this slide the container call the servlets
service() method which will then invoke the servlets
doGet() method as we originally passed across a HTTP GET method.
In this slide the servlets
doGet() method create a dynamic page and passes it back to the container via the HttpServletResponse object.
In this final slide the container passes the HTTP response back to the client for rendering.
Hopefully you can see from the slideshow the key role the web container has in the handling of a servlet request. There are also questions that arise from looking through the slideshow such as how does a request
get mapped to the required servlet and what is the
service() method of a servlet? We will endeavour to answer these questions as we work through the rest of the basic lessons. But before we go into
more details about servlets its worth taking a look at the deployment environment structure and the anatomy of the Deployment Descriptor (DD) which are the topics of the rest of the lesson along with the well known
MVC design pattern.
Tomcat Deployment Environment
Dependant upon the container being used the deployment environment structure can vary slightly. As we are using for these tutorials the container specific parts of the deployment structure pertain to this particular web container. The following file structure shows the deployment environment and where appropriate those parts that are container and application specific.img class="responsive" src="../images/tomcatdeploy.jpg" alt="Tomcat Deployment Environment" title="Tomcat Deployment Environment" width="730" height="558">
There are several interesting points worth going into more detail about than the captions in the above diagram provide. Tomcat expects all web applications to be within the
webapps folder and apart from
the view components which are shown in the diagram as static (HTML) and dynamic (JSP) pages everything else is hidden within the
WEB-INF folder. This stops malicious attacks on the contents of this folder
and keeps everything within it private and only accessible via the container, whilst allowing users to directly access the view components we want them to. The
web.xml file holds the Deployment Descriptor (DD)
for our web application and it is within this xml file that we can put declarative statements to avoid code pollution. We have put our classes into separate folders called model and controller and we will go into
more details about separation of concerns a bit later in the lesson when we look at the MVC design pattern.
Deployment Descriptor (DD)
web.xml file is our Deployment Descriptor (DD) and is where we put declarative statements for several areas of our web application. We will expand on the DD as we move through the lessons but for now
we will take a brief look at the structure of the DD. The first part of the file is always the same and points to version numbers, schemas and namespaces for XML and DTD, so don't worry too much about this when creating your own DD, just copy it.
<?xml version="1.0" encoding="UTF-8"?> <web-app xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" version="2.5"> </web-app>
What we are interested in are the top-level elements within the
web-app document root element. All top-level elements are optional, and can be in any order, but we are are displaying them in
alphabetical order in the following diagram:
Most of the top-level elements shown above contain nested elements within them which we will look at in more detail in the appropriate places within these tutorials, but you can see the general structure from the diagram above. You can also look at the DD Elements At A Glance quick reference, where all the DD elements are explained in detail so we won't go into them here. Correct use of the DD takes a lot of code pollution out of servlets and allows us to declaratively prescribe areas of our web applications which can be changed in just one place when needed. For these reasons we will spend a lot of time in forthcoming tutorials focusing on parts of the DD relevant to the lesson in question.
The Model-View-Controller Pattern
The processing involved to get even a simple web application implemented can be quite complex and so various design patterns have emerged over the years to simplify the design of such systems. Perhaps the best known of these patterns, which also fits into the three-tier architecture pattern used for this site, and the one we will talk about and use within these tutorials is the Model-View-Controller (MVC) Pattern. The aim of the MVC pattern is to separate the tasks involved in creating a GUI application into three areas, these being as the name suggests the Model, View and Controller areas. Using this pattern we can keep these regions of the application separate from each other and in the real world it's not uncommon to have different teams that specialize in and develop each region of this pattern in isolation. An added benefit of this approach is that the different parts of the system are not tightly coupled, meaning we can make changes to one part of the system without hugely impacting the rest of it. There are many variations on the MVC pattern and the diagram below is perhaps a more classic interpretation of the pattern where the view gets updated directly from the model.
The different areas covered in the MVC pattern are discussed in the subsections below.
The Model acts as an interface to the underlying system state, data and application logic. The job of the Model is to provide a consistent way to retrieve and manipulate state held within an application. The Model knows nothing of the View and Controller parts of the pattern although changes to state can be notified to observers. This has the added benefit of reusability as our Model is not coupled to any specific View or Controller and so can be reused via its interface.
The View is the physical representation of the data presented in a format suitable for the user of the data. The format in regards to these lessons is a HTML of JSP page, but the format could just as easily be a JSON or XTML document. The point is, it is the responsibility of the View to format the data appropriately for whatever usage is required. The View also has the responsibility of interpreting user interaction where appropriate and handling and dispatching user actions as required.
The Controller allows the abstraction between the presentation and data tiers by acting as an intermediary between the View and the Model. This means that any requests by users should always be passed from the View to the Controller which will then call the Model as and when required. This separation of concerns decreases the complexity within each tier of our architecture and enhances reusability.
How Java Fits In
When developing our own web application we can develop the Model (data tier) and Controller (application tier) using Core Java which can be learned in the first seven sections of the Java section of the site. For our View (presentation tier) we would use static HTML pages or dynamic JSP pages.
Lesson 3 Complete
In this lesson we looked at the Java EE5 Platform and how servlets fit into the architecture and then discussed the MVC design pattern, which we will use in the rest of the tutorials for creating our own web applications on the site.
In the next lesson we look at an overview of the servlet hierarchy and the classes and methods therein.