Articles
Java Platform, Standard Edition
|
| |
Java Servlet technology and JavaServer Pages (JSP pages) are server-side technologies that have dominated the server-side Java technology market; they've become the standard way to develop commercial web applications. Java developers love these technologies for myriad reasons, including: the technologies are fairly easy to learn, and they bring the Write Once, Run Anywhere paradigm to web applications. More importantly, if used effectively by following best practices, servlets and JSP pages help separate presentation from content. Best practices are proven approaches for developing quality, reusable, and easily maintainable servlet- and JSP-based web applications. For instance, embedded Java code (scriptlets) in sections of HTML documents can result in complex applications that are not efficient, and difficult to reuse, enhance, and maintain. Best practices can change all that.
In this article, I'll present important best practices for servlets and JSP pages; I assume that you have basic working knowledge of both technologies. This article:
Similar to Common Gateway Interface (CGI) scripts, servlets support a request and response programming model. When a client sends a request to the server, the server sends the request to the servlet. The servlet then constructs a response that the server sends back to the client. Unlike CGI scripts, however, servlets run within the same process as the HTTP server.
When a client request is made, the
service method is called and passed a request and response object. The servlet first determines whether the request is a
GET or
POST operation. It then calls one of the following methods:
doGet or
doPost. The
doGet method is called if the request is
GET, and
doPost is called if the request is
POST. Both
doGet and
doPost take request (
HttpServletRequest) and response (
HttpServletResponse).
In the simplest terms, then, servlets are Java classes that can generate dynamic HTML content using
print statements. What is important to note about servlets, however, is that they run in a container, and the APIs provide session and object life-cycle management. Consequently, when you use servlets, you gain all the benefits from the Java platform, which include the sandbox (security), database access API via JDBC, and cross-platform portability of servlets.
The JSP technology--which abstracts servlets to a higher level--is an open, freely available specification developed by Sun Microsystems as an alternative to Microsoft's Active Server Pages (ASP) technology, and a key component of the Java 2 Enterprise Edition (J2EE) specification. Many of the commercially available application servers (such as BEA WebLogic, IBM WebSphere, Live JRun, Orion, and so on) support JSP technology.
How Do JSP Pages Work?
A JSP page is basically a web page with traditional HTML and bits of Java code. The file extension of a JSP page is .jsp rather than .html or .htm, which tells the server that this page requires special handling that will be accomplished by a server extension or a plug-in.
When a JSP page is called, it will be compiled (by the JSP engine) into a Java servlet. At this point the servlet is handled by the servlet engine, just like any other servlet. The servlet engine then loads the servlet class (using a class loader) and executes it to create dynamic HTML to be sent to the browser, as shown in Figure 1. The servlet creates any necessary object, and writes any object as a string to an output stream to the browser.
The next time the page is requested, the JSP engine executes the already-loaded servlet unless the JSP page has changed, in which case it is automatically recompiled into a servlet and executed.
In this section, I present best practices for servlets and particularly JSP pages. The emphasis on JSP best practices is simply because JSP pages seem to be more widely used (probably because JSP technology promotes the separation of presentation from content). One best practice that combines and integrates the use of servlets and JSP pages is the Model View Controller (MVC) design pattern, discussed later in this article.
<%@ include file="filename" %>
<jsp:include page="page.jsp" flush="true" />
<c:import> action tag provided by the JavaServer pages Standard Tag Library (JSTL). You can use this tag to bring in, or import, content from local and remote sources. Here are some examples:
<c:import url="./copyright.html"/> <c:import url="http://www.somewhere.com/hello.xml"/>
<someTags:aTag attribute="<%=
pageContext.getAttribute("aName") %>">
or the value of a custom JavaBeans component:
<%= aCustomer.getAddress().getCountry() %>
An expression language allows a page author to access an object using a simplified syntax. For example, to access a simple variable, you can use something like:
<someTags:aTag attribute="${aName}">
And to access a nested JavaBeans property, you would use something like:
<someTags.aTag attribute="${
aCustomer.address.country}">
If you've worked with JavaScript, you will feel right at home, because the EL borrows the JavaScript syntax for accessing structured data.
HttpSession object, which provides a simple and convenient mechanism to store information about users, and uses cookies to identify users. Use sessions for storing temporary information--so even if it gets lost, you'll be able to sleep at night. (Session data is lost when the session expires or when the client changes browsers.) If you want to store persistent information, use a database, which is much safer and portable across browsers.
ResultSet object as the cache object. This is tightly linked to a connection that conflicts with the connection pooling. Copy the data from a
ResultSet into an application-specific bean such as
Vector, or JDBC's
RowSets.
The JSP specification presents two approaches for building web applications using JSP pages: JSP Model 1 and Model 2 architectures. These two models differ in the location where the processing takes place. In Model 1 architecture, as shown in Figure 2, the JSP page is responsible for processing requests and sending back replies to clients.
The Model 2 architecture, as shown in Figure 3, integrates the use of both servlets and JSP pages. In this mode, JSP pages are used for the presentation layer, and servlets for processing tasks. The servlet acts as a controller responsible for processing requests and creating any beans needed by the JSP page. The controller is also responsible for deciding to which JSP page to forward the request. The JSP page retrieves objects created by the servlet and extracts dynamic content for insertion within a template.
This model promotes the use of the Model View Controller (MVC) architectural style design pattern. Note that several frameworks already exist that implement this useful design pattern, and that truly separate presentation from content. The Apache Struts is a formalized framework for MVC. This framework is best used for complex applications where a single request or form submission can result in substantially different-looking results.
Best practices -- which are proven solutions to recurring problems -- lead to higher quality applications. This article presented several guidelines and best practices to follow when developing servlet- and JSP-based web applications.
Keep an eye on servlets and JSP technologies, because several exciting things are in the works. JavaServer Faces (JFC), for example, a Java Community Process effort that aims to define a standard web application framework, will integrate nicely with Apache Struts.
Tomcat
Servlets
JavaServer Pages
Enterprise BluePrints
Apache Struts
Code Conventions for the JavaServer Pages Technology Version 1.x Language
Java Server Faces (JSF)
Special thanks to Gregory Murray of Sun Microsystems, whose feedback helped me improve this article.
Qusay H. Mahmoud provides Java consulting and training services. He has published dozens of articles on Java, and is the author of Distributed Programming with Java (Manning Publications, 1999) and Learning Wireless Java (O'Reilly, 2002).