22
Sun, Dec
3 New Articles

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

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: