Scripting Syntax Error Examples

Let’s look at some examples of problems you need to deal with if you use scripting elements.

Example 16-7 shows a modified version of the page used earlier to illustrate how scripting elements end up in the generated servlet. It has two errors: a semicolon is incorrectly used in the expression, and the closing bracket for the else block in the last scriptlet is missing.

Example 16-7. Invalid semicolon use and missing end bracket (error1.jsp)
<%@ page language="java" contentType="text/html" %>
<%@ page import="java.util.Date" %>
<%!
  private String getGreeting(  ) {
    Date now = new Date(  );
    String greeting = null;
    if (now.getHours(  ) < 12) {
      greeting = "Good morning";
    }
    else if (now.getHours(  ) < 18) {
      greeting = "Good day";
    }
    else {
      greeting = "Good evening";
    }
    return greeting;
  }
%>
<html>
  <head>
    <title>Invalid semicolon use and missing end bracket</title>
  </head>
  <body bgcolor="white">
    <%= getGreeting(  ); %>
    <% if (request.getParameter("name") == null) { %>
      stranger!
    <% } else { %>
      partner!
  
    How are you?
  </body>
</html>

This is the error description Tomcat sends to the browser (with some line breaks added to make it fit the page):

org.apache.jasper.JasperException: Unable to compile class for JSP An error occurred at line: 24 in the jsp file: /ch16/error1.jsp Generated servlet error: D:\jakarta-tomcat-5.0\work\localhost\ora\ch16\error1_jsp.java:67: ')' expected. out.write(String.valueOf(getGreeting( ); )); ^ An error occurred at line: 24 in the jsp file: ...

Get JavaServer Pages, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.