Mixing Static Data with Scriptlets for Compound Statements

This section provides a tutorial example on how to mix static data with scriptlets to form Java compound statements like 'if', or 'while'.

One thing interested the most in writing JSP scriptlets is how you can mix static data and scriptlets together to form compound Java statements like "if" or "while" statements. Here is a simple example:

<html><body>
<!-- Mixed_Scripting.jsp
   Copyright (c) 2012, HerongYang.com, All Rights Reserved.
-->
<pre>
Mixed "if" statement:
<% java.util.Calendar now = java.util.Calendar.getInstance();
   if (now.get(java.util.Calendar.AM_PM) == java.util.Calendar.AM) {
%>
Good Morning
<% } else { %>
Good Afternoon
<% } %>
</pre>
</body></html>

My guess is that the converted Java class should have the following code fragment:

   java.util.Calendar now = java.util.Calendar.getInstance();
   if (now.get(java.util.Calendar.AM_PM) == java.util.Calendar.AM) {
      out.write("Good Morning");
   } else {
      out.write("Good Afternoon");
   }

If you deploy the JSP page, Mixed_Scripting.jsp, to Tomcat 7, and visit it with a browser, Tomcat 7 will convert it to: Mixed_005fScripting_jsp.java:

...
out.write("<html><body>\r\n");
out.write("<!-- Mixed_Scripting.jsp\r\n");
out.write(
   "   Copyright (c) 2012, HerongYang.com, All Rights Reserved.\r\n");
out.write("-->\r\n");
out.write("<pre>\r\n");
out.write("Mixed \"if\" statement:\r\n");
 java.util.Calendar now = java.util.Calendar.getInstance();
   if (now.get(java.util.Calendar.AM_PM) == java.util.Calendar.AM) {

out.write("\r\n");
out.write("Good Morning\r\n");
 } else { 
out.write("\r\n");
out.write("Good Afternoon\r\n");
 } 
out.write("\r\n");
out.write("</pre>\r\n");
out.write("</body></html>\r\n");
...

Pretty close to my guess, except that there some extra (out.write("\r\n");) statements.

Last update: 2012.

Table of Contents

 About This Book

 JSP (JavaServer Pages) Overview

 Tomcat 7 Installation on Windows Systems

JSP Scripting Elements

 What Are Scripting Elements?

 Converting JSP Pages with Scripting Elements

 Example JSP Page with Scripting Elements

 Example Java Class Converted from a JSP Page

Mixing Static Data with Scriptlets for Compound Statements

 Java Servlet Introduction

 JSP Implicit Objects

 Syntax of JSP Pages and JSP Documents

 JSP Application Session

 Managing Cookies in JSP Pages

 JavaBean Objects and "useBean" Action Elements

 Managing HTTP Response Header Lines

 Non-ASCII Characters Support in JSP Pages

 Performance of JSP Pages

 EL (Expression Language)

 Overview of JSTL (JSP Standard Tag Libraries)

 JSTL Core Library

 JSP Custom Tags

 JSP Java Tag Interface

 Custom Tag Attributes

 Multiple Tags Working Together

 File Upload Test Application

 Outdated Tutorials

 References

 PDF Printing Version