Java Journal: JavaServer Pages (JSPs)

Java
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times
In last month's "Java Journal," I showed you how to get your Java Web development feet wet with servlets. As a follow-up, this month I will show you how to go wading on the other side of the Java Web development ocean using JavaServer Pages (JSPs). To help highlight the similarities and differences between servlets and JSPs, this month's article will parallel last month's article. So grab your suit, and let's hit the beach.

As discussed in last month's article, one of the most common uses of servlets is to generate dynamic HTML responses to HTTP requests. In other words, servlets can be used to create dynamic Web pages. However, servlets suffer from a critical flaw. All of the HTML tags that they generate must be embedded in the Java source code. While this is easy enough to do for a few Web pages, it does not scale well. Imagine what would happen if your company decided to change the corporate look and feel of the Web site and all of your HTML tags were embedded in your Java source code. You would have to change a lot of Java source code. Servlets also don't scale well for complicated Web pages. Since the Web pages are only generated at runtime, doing complicated layouts can be time-consuming. So what you need is a technology that allows you to generate your Web pages as templates and then make calls to your server-side Java code to fill in the dynamic parts. JSPs help you to do exactly this.

Although you only see it conceptually, it is important to know that JSPs are built on top of servlets. The JSP engine, also called a "JSP container" in some contexts, translates JSPs into servlets on the fly. This takes care of lots of details that you would rather not be bothered with. JSP files look exactly like regular HTML files except they have a .jsp extension and they may contain JSP scripting elements. These elements are broken down into three categories: expressions, scriptlets and declarations. JSP expressions are simple Java expressions that are evaluated by the JSP engine, converted to strings, and then inserted into the output stream. Scriptlets are snippets of Java source code that are evaluated by the JSP engine and have access to some predefined Java variables, such as request, response, out, session, config, and others. Unlike expressions, scriptlets must explicitly write to the out stream to generate output. Declarations let you define class-level fields and even methods that become part of the servlet class handling your request. Just like any other class-level method, you have to be careful with thread safety when using declarations.

What You Will Need

If you have already configured your system according to last month's article, you are ready to work with JSPs now and can skip the following instructions. Otherwise, to get started with JSPs, you will need two pieces of software: Tomcat and a current Java Developer Kit (JDK) from Sun. Any version 1.2 or higher of the JDK should work, although I used 1.4 when developing my examples. You can get the JDK 1.4 here. Accept all the defaults on the installers. You can get a copy of Apache's servlet/JSP container called Tomcat 4.0.4 from here. Install it and accept all the defaults. The Tomcat installer will put convenience shortcuts on your Start menu under Apache Tomcat for starting and stopping the server. Start the Tomcat server, which by default will be listening on port 8080. You can test that Tomcat is installed correctly by pointing your Web browser to http://localhost:8080/, which should take you to a page congratulating you on your successful installation of Tomcat.

Configuration

Now, you need to create a place within the Tomcat tree to place your JSPs and then configure Tomcat to know where this is. First, create a folder called jspExample under Apache Tomcat 4.0webapps. Then, add the following entry to the server.xml file located in the Apache Tomcat 4.0conf folder:


  docBase="C:Program FilesApache Tomcat 4.0webappsjspExample">


Not only does this little snippet of XML tell Tomcat where you are going to store your JSPs, it also decouples the physical location on the C: drive from the logical location by creating an alias to this location called jspTest. All requests coming into Tomcat will only know about the logical location.

The Good Stuff


Now, I'll give you four examples to try.

Example 1

For the first example, you will create a JSP file called serverTime.jsp that uses a JSP expression to return the current date and time on the server:


  
    Server Time: 
    <%= new java.util.Date() %>
  


Put serverTime.jsp in the C:Program FilesApache Tomcat 4.0webappsjspExample that you created previously. Then, with your favorite Web browser, invoke it using http://localhost:8080/jspTest/serverTime.jsp. This should return a rather plain-looking Web page containing the current time on the server. Note that you didn't need to create any server-side code to handle this request.

Example 2

Although there is nothing wrong with the first example, you can add a little syntactic sugar by wrapping your request in XML syntax. Either method is acceptable, although I personally find the XML version a little more concise:


  
    
      Server Time: 
       
  new java.util.Date()
      
    
  

Example 3

Next, you will use a scriptlet that is functionally equivalent to the previous expression examples:  


  
    
      Server Time 
       
  String temp = (new java.util.Date()).toString();
  out.println(temp);
      
    
  

Example 4

In this example, you will use a declaration to create a simple counter that tracks how many times you have checked the time:


  
    
      Server Time 
      
        private int count = 0;
      
       
  String temp = (new java.util.Date()).toString();
  out.println(temp);
  out.println("Count = " + count);
          count++;
      
    
  


This example works because the variable count is a class-level variable and thus maintains value from one invocation of the servlet generated by the JSP to the next. Note that the servlet is generated on the first invocation of the JSP. This results in two issues that you should be aware of. First, your server may have a ramp up time. If you have a lot of complicated JSPs, you may want to run a script that calls each of them on startup of your server so that the system is primed and your users do not experience any startup latency just because they are the first user to request a JSP after a server restart. Second, these generated servlet classes only live until the server is shut down. So unless you provide for some sort of persistent storage, variables, such as count in the previous example, are lost when the server is shut down.

Why to Use

If you think of HTTP servlets as allowing you to embed HTML in Java, then JSPs are the reciprocal in that they allow you to embed Java into HTML. There are three reasons embedding Java in HTML works better than embedding HTML in Java. First, when you create HTML, you want to use a good Web authoring tool that allows you to spend most of your time using visual tools to do layout and as little time as possible actually writing HTML tags. This way, when you make a change, you immediately know what the page will look like without having to compile and run a test as you would if you were not using JSPs. Second, when you embed HTML in Java, you have to put all of the HTML in the Java source code or in files that the Java source code reads. When you embed Java in HTML, you can embed as little as one line of Java code, which calls the rest of Java code that does all the heavy lifting. Third, embedding Java in HTML allows you to partition your team into Web developers that lay out Web pages and write simple Java method calls, and Java developers that write just the Java code that does all the heavy lifting. This is a much easier practice than forcing your Web developers to wrap all of their HTML in Java source code.

Why Not to Use

Well, there's really no reason you shouldn't use JSPs; you should just be careful. Avoid creating large scriptlets. Instead, use your scriptlets to talk to Enterprise JavaBeans (EJBs) or other services, and allow the bulk of your logic to reside there. The code within JSPs is not reusable, so if at all possible, push any logic off to somewhere else. Also, remember that on-the-fly creation of a servlet by a JSP means that any syntax errors are not caught until runtime.

Conclusion

Although JSPs are built on top of servlets, JSPs are far easier to configure and use for dynamic HTML creation than servlets are. JSPs allow you to easily divide your development efforts between HTML Web developers and server-side Java developers. And, as with servlets, you don't need a full-blown, expensive Java 2 Enterprise Edition (J2EE) server to get started. Instead, you can just use a simple servlet/JSP container such as Apache's Tomcat. But remember: Although JSPs have many advantages, it is prudent to put as little logic as possible in your JSPs.

Michael J. Floyd is an Extreme Programmer and the Software Engineering Technical Lead for DivXNetworks. He is also a consultant for San Diego State University and can be reached at This email address is being protected from spambots. You need JavaScript enabled to view it.. He is also the proud father of his brand new baby girl, Brianna Ashleigh.

BLOG COMMENTS POWERED BY DISQUS