We saw last time that J2EE is a platform for building distributed, component based applications, although we didn’t really mention that there are a number of ways in which this functionality can be exposed and delivered to the end user - be it a human or an automated user. Examples here include a traditional desktop GUI application, a web service, an application running on a mobile phone/PDA or, more commonly, a web-based browser interface. J2EE provides two technologies for building web based applications - Java Servlets and JavaServer Pages (JSP).
Java Servlets was really the first true server-side Java technology and, at a high level, is simply the Java equivalent of CGI scripts. From an implementation perspective, servlets are simply Java classes that implement a predefined interface. The following example illustrates how to write a servlet that outputs an HTML page containing the current date, formatted in an appropriate way for the user’s locale.
package mypackage; import java.io.*; import java.text.*; import java.util.*; import javax.servlet.http.*; import javax.servlet.ServletException; public class DateServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // get a reference to the output writer PrintWriter out = response.getWriter(); // get the locale of the client and create an appropriate date format Locale loc = request.getLocale(); DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, loc); // and generate the page out.println("<html>"); out.println("<head>"); out.println("<title>The current date</title>"); out.println("<link rel=\"stylesheet\" href=\"../page.css\">"); out.println("</head>"); out.println("<body>"); out.println("<h1>The date is "); out.println(df.format(new Date())); out.println("</h1>"); out.println("</body>"); out.println("</html>"); out.flush(); out.close(); } }
As this shows, servlets are fairly simple to build although even with this short example, a great deal of static content is embedded within the source code. However, servlets expand and improve on the concept of CGI because they address the two major issues that we mentioned earlier - integration and the execution model.
Where a new process will be created for each and every request in the CGI model, servlets are simply objects that run inside a container provided by a third party such as BEA, IBM and so on. Depending on which servlet container you use, there could be one or more instance of each servlet ready to service incoming requests, made possible by utilising Java’s threading model. For this reason, servlets are a much more scalable alternative to CGI scripts because rather than creating a new process to service a request, each request can be serviced by a different thread.
The other aspect that is greatly improved over the CGI model is that of integration. Since servlets are written in Java, they have access to the rich library of features provided by Java, including access to databases and other enterprise resources such as Enterprise JavaBeans (EJB). In essence, it is possible to achieve a great deal without ever leaving the Java environment.
out.println()
calls. From an implementation perspective, JSP is written as pages (e.g. HTML files) and can have embedded within them fragments of Java source code known as scriptlets. These scriptlets are a mechanism for adding dynamic behaviour into otherwise static content. A JSP version of the previous example is as follows.
<html> <head> <title>The current date</title> <link rel="stylesheet" href="../page.css"> </head> <%@ page import="java.text.*" %> <%@ page import="java.util.*" %> <body> <% // get the locale of the client and create an appropriate date format Locale loc = request.getLocale(); DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, loc); %> <h1>The date is <%= df.format(new Date()) %></h1> </body> </html>
As this shows, JSP pages are really just static content (in this case HTML) with special tags and characters. In this example, first of all we have directives that specify something about the JSP page (<%@ ... %>
), then we have scriptlets that contain regular Java code (<% ... %>
) and finally we have expressions (<%= ... %>
), the results of which get output to the page.
<html> <head> <title>The current date</title> <link rel="stylesheet" href="../page.css"> </head> <%@ taglib uri="/dateTaglib" prefix="date" %> <body> <h1>The date is <date:currentDate/></h1> </body> </html>
In this example, all of the Java code has been removed from the page and is now wrapped up and encapsulated as a reusable component. From an implementation perspective, custom tags are essentially just Java classes that again implement a specific interface. However, JSP 2.0 introduces the notion of building custom tags as fragments of JSP pages meaning that people that are not familiar with the Java programming language can also take advantage of custom tags to wrap up reusable functionality.
Building custom tags to represent common and recurring functionality is a great way to increase the maintainability of web applications while also making them easier to understand and read, particularly for page authors - those people that are focussed on the look and feel of an application rather than its functionality. After all, the amount of code on the page, mixed in with the content, is dramatically reduced.
Another good reason for using custom tags is that, through reuse, they can help decrease the time required to build web applications, and therefore decrease your time to market. There are currently many open source tag libraries (collections of custom tags) available to download from the Internet, and a good source of these is the Jakarta Taglibs project. Included in this collection of tag libraries is the JSP Standard Tag Library (JSTL) - an implementation of an initiative managed through the Java Community Process for the development of a standard tag library that can be used and reused for building JSP-based web applications. Essentially, JSTL contains a number of custom tags that help to solve many of the common problems encountered while building web applications, ranging from iterating over collections, delivering localized content and manipulating XML documents.
In reality, the answer to this question lies in how we use servlets and JSP pages, rather than any specific technical differences. Servlets are written in the same way as you would write regular Java classes and it’s for this reason that they are more suited to delivering content that is easy to generate programmatically. In other words, servlets are useful where there is more code (logic) than content (for example HTML). JSPs are more useful in buiding the presentation side of web applications because generating dynamic content is much easier if you are writing much of that content in its native form. We'll be seeing more about how servlets and JSP pages coexist when we look in detail at J2EE design patterns and application architectures in a future article.
With our brief tour of the J2EE web tier complete, the next article will look at the business tier and specifically Enterprise JavaBeans.