Home > Articles > Programming > Java

This chapter is from the book

19.3 How to Write a JSP Application

Writing a JSP application consists, syntax-wise, of writing your desired output page in HTML and, where you need the dynamic bits, putting Java code and/or other special syntax inside special delimiters that begin with <%.

There are four special delimiters that we should describe if you're going to work with JSP. The bulk of your JSP will likely be HTML. But interspersed among the HTML will be Java source or JSP directives, inside of these four kinds of delimiters:

  • <% code %>
  • <%= expression %>
  • <%! code %>
  • <%@ directive %>

Let's look at them one at a time.

19.3.1 Scriptlet

The code that appears between the <% and %> delimiters is called a scriptlet. By the way, we really hate the term "scriptlet." It seems to imply (falsely) a completeness that isn't there. It is too parallel to the term "applet," which is a complete Java program that runs inside a browser. A scriptlet isn't necessarily a complete anything. It's a snippet of code that gets dropped inside the code of the servlet generated from the JSP source.

Recall that servlets may have a doPost() and a doGet() methods, which we collapsed in our example by having them both call the doBoth() method. Same sort of thing is happening here with the JSP, and the doBoth() ends up doing all the output of the HTML. Any snippets of Java code from within the <% and %> delimiters get dropped right in place between those output calls, becoming just a part of a method.

It can be useful to keep this in mind when writing JSP. It helps you answer the questions of scope—who has access to what, where are variables getting declared and how long will they be around? (Can you answer that last question? Since any variable declared inside the <% and %> will be in the JSP equivalent of our doBoth() method, then that variable will only be around for the duration of that one call to the doBoth(), which is the result of one GET (or POST) from the browser.)

The source code snippets can be just pieces of Java, so long as it makes a complete construct when all is converted. For example, we can write:

<% if (acct != null) { // acct.getParent() %>
    <a href="BudgetPro?func=back">
    <img src="/back.gif">
    </a>
<% } else { %>
    <img src="/back.gif">
<% } %>

Notice how the if-else construct is broken up into three separate scriptlets—that is, snippets of code. Between them, in the body of the if and the else, is plain HTML. Here is what that will get translated into after the JSP conversion:

if (acct != null) { // acct.getParent()
    out.println("<a href=\"BudgetPro?func=back\">");
    out.println("<img src=\"/back.gif\">");
    out.println("</a>");
} else {
    out.println("<img src=\"/back.gif\">");
}

Do you also see why we describe it as being "turned inside out"? What was delimited becomes undelimited; what was straight HTML becomes delimited strings in output statements.

As long as we're on the topic of conversion, let's consider comments. There are two ways to write comments in JSP, either in HTML or in Java. In HTML we would write:

<!-- HTML comment format -->

but since we can put Java inside of delimiters, we can use Java comments, too:

<% // Java comment format %>

or even:

<% /*
       * Larger comments, too.
       */
%>

If you've been following what we've been saying about translation of JSP into Java code, you may have figured out the difference. The Java comments, when compiled, will be removed, as all comments are, from the final executable.

The HTML-based comments, however, will be part of the final HTML output. This means that you'll see the HTML comments in the HTML that reaches the browser. (Use the View Source command in your browser to see them. As HTML comments, they aren't displayed on the page, but they are sent to the browser.) This is especially something to be aware of when writing a loop. Remember our loop for generating the table?

<% // for each subaccount:
  for (Iterator actit = acct.getAllSubs(); actit.hasNext(); ) {
    Account suba = (Account) actit.next();
%>
    <!-- Next Row -->
    <tr>
    <td><a href="BPControl?name=<%= suba.getName() %>&func=cd">
...
<% } // next acct %>

We've put a comment just prior to the <tr> tag. What will happen is that the comment will be part of the generated HTML, and since this is a loop, the comment, just like the <tr> and other tags, will be repeated for each iteration of the loop. Now we're not saying this is undesirable—in fact it makes the resultant HTML more readable. But be aware that these comments will be visible to the end user. Be careful in what you say in them. The additional transmission time required for these few extra bytes is probably imperceptible, unless your comments are large and repeated many times.

19.3.2 Declaration

The other place that code can be placed is outside the doGet() and doPost(). It is still inside the class definition for the servlet class that gets generated from the JSP, but it is not inside any method. Such code is delimited like this:

<%! code %>

The exclamation mark makes all the difference. Since it's outside any method, such code typically includes things like variable declarations and complete method declarations. For example:

<%! public static MyType varbl;

public long
countEm()
{
    long retval = 0L;
    retval *= varbl.toLong();
    return retval;
}
%>

If you tried to do something like this inside of a scriptlet, you would get errors when the server tries to compile your JSP. Such syntax belongs at the outer lexical level. The use of the <%! ... %> syntax puts it there.

19.3.3 Expression

This delimiter is a shorthand for getting output from a very small bit of Java into the output stream. It's not a complete Java statement, only an expression that evaluates into a String. Here's an example:

<h4>As of <%= new java.util.Date() %></h4>

which will create a Java Date object (initialized, by default, with the current date/time) and then call the toString() method on that object. This yields a date/time stamp as part of an <h4> heading.

Any methods and variables defined inside the previously described delimiters are OK to use with this expression shorthand.

There are also a few predefined servlet variables.

We've described how the JSP is converted into a servlet—the HTML statements become println() calls. This all happens inside of an HttpServlet-like class, just like our BudgetProServlet extends HttpServlet in the previous chapter. In such a class, the method called when a request arrives from a browser looks very much like our doBoth() method:

doBoth(HttpServletRequest request, HttpServletResponse response)

The point here is that a request object and a response object are defined by the way the servlet is generated. They are called, oddly enough, request and response. In addition to these, a session is defined and initialized, just like we did in our servlet example. (What were we thinking?)

There are a few other variables that the converted servlet has created that we can use. We'll summarize them in Table 19.1. To read more about how to use them, look up the Javadoc page for their class definition.

Table 19.1. JSP predefined variables

Type

Variable name

PageContext

pageContext

HttpSession

session

ServletContext

application

ServletConfig

config

JspWriter

out

Remember that these can be used not only by the <%= %> expressions, but also by the <% %> snippets of code.

19.3.4 Directive

The last of the special delimiters that we will discuss is the one that doesn't directly involve Java code. The <%@ ... %> delimiter encompasses a wide variety of directives to the JSP converter. We don't have the space or the patience to cover them all, so we'll cover the few that you are most likely to need early on in your use of JSP. We have some good JSP references at the end of this chapter for those who want all the gory details of this feature.

<%@page import="package.name.*" %>

is the way to provide Java import statements for your JSP. We bet you can guess what that happens in the generated servlet.

Here's another useful page directive:

<%@page contentType="text/html" %>

You'll see this as the opening line of our JSP, to identify the output MIME type for our servlet.

JSP also has an include directive:

<%@include file="relative path" %>

This directive is, for some applications, worth the price of admission alone. That is, it is such a useful feature that even if they use nothing else, they could use JSP just for this feature. It will include the named file when converting the JSP—that is, at compile time.

It can be used for common header and footer files for a family of Web pages. (If you're a C programmer, think #include.) By defining one header file and then using this directive in each JSP, you could give all your JSP the same look—say, a corporate logo and title at the top of page and a standard copyright statement and hyperlink to your webmaster's e-mail address at the bottom.

Be aware that this inclusion happens at compile time and is a source-level inclusion. That is, you are inserting additional source into the JSP, so if your included file contains snippets of Java code, they will be part of the resulting program. For example, you could define a variable in the included file and reference in the including file.

Also, since this inclusion happens at compile time, if you later change the included file, the change will not become visible until the JSP files that do the including are recompiled. (On Linux, this is simply a matter of touching all the JSP, as in:

$ touch *.jsp

assuming all your JSP files are in that directory. Touching them updates their time of last modification, so the Web server thinks they've been modified so the next access will cause them to be reconverted and their generated servlets reloaded. You get the idea.

There is another way to do an include in JSP—one that happens not at compile time, but at runtime. The syntax is different than the directives we've seen so far, but more on that in minute. First, an example of this kind of include:

<jsp:include page="URL" flush="true" />

In this format, the page specified by the URL (relative to this Web application's root) is visited and its output is included in place amongst the output of this JSP, the one doing the include.

A few quick notes:

  • Be sure to include the ending "/" in the directive; it's part of the XML syntax which is a shorthand for ending the element in the same tag as you begin—that is, <p /> instead of <p> </p>.
  • When all is working, flush being true or false doesn't matter; when the included page has an error, then flush="true" causes the output to the browser to end at the point of the include; with flush="false", the rest of the page will come out despite the error in the include.
  • The page that is being included is turned into its own servlet. That is, it is its own JSP. You don't have to just include static HTML, you can include a JSP.
  • Since this is a runtime include, all you are including is the output of that other page. You can't, with this mechanism, include Java snippets or declarations, but only HTML output.

19.3.5 New Syntax

But what about that new syntax? It's an XML-conformant syntax, and it's the syntax for all the newer features added to JSP. In fact, even the old JSP syntax, the statements that we've discussed, have an alternative new syntax (Table 19.2). Prior to JSP 2.0, that syntax was reserved for JSP that produce XML rather than HTML. (That's a whole other can of worms that we won't open now.) Now, as of JSP 2.0, both forms can be used, if your Web server is JSP 2.0 compliant.

Table 19.2. New XML syntax for JSP constructs

Standard format

New HTML format

<% code %>

<jsp:scriptlet> code </jsp:scriptlet>

<%! code %>

<jsp:declaration> code </jsp:declaration>

<%= expr %>

<jsp:expression> expr </jsp:expression>

You can see that the old syntax is more compact and less distracting than the large tags. We suspect that means the old syntax is likely to continue to be used for a long time yet. [1]

This new syntax is also used for the last two parts of JSP that we will cover, useBean and tag libraries.

19.3.6 JavaBeans in JSP

For those who really want to avoid doing any Java coding inside of a JSP, there is additional syntax that will provide for a lot of capability but without having to explicitly write any Java statements. Instead, you write a lot of arcane JSP directives, as we'll show you in just a bit. Is this any better? In some ways yes, but in other ways, no, it's just different syntax.

What we'll be able to do with this additional syntax is:

  1. Instantiate a Java class and specify how long it should be kept around
  2. Get values from this class
  3. Set values in this class

The syntax looks like this:

<jsp:useBean id="myvar" class="net.multitool.servlet.AccountBean" />

which will create a variable called myvar as an instance of the AccountBean class found in the net.multitool.servlet package. Think of this as:

<%! import net.multitool.servlet.AccountBean; %>

<% AccountBean myval = new AccountBean(); %>

So can AccountBean be any class? Well, sort of. It can be any class that you want, as long as it is a bean. It doesn't have to end in "Bean", but it does have to be a class which has:

  • A null constructor (you may have noticed there is no syntax to support arguments to the constructor on the useBean statement).
  • No public instance variables.
  • Getters and setters for instance variables.
  • Getters and setters named according to a standard: getTotal() or isTotal() and setTotal() for a variable called total (isTotal() would be used if we had a boolean getter, that is, if the getter returned a boolean; otherwise it would expect getTotal() as the getter's name).

Otherwise, its a normal class. These restrictions mean that you can call the class a "JavaBean" or just "bean," and there is additional JSP syntax to manipulate the class. Specifically:

<jsp:getProperty name="myvar" property="total" />

will do, in effect, the following:

<%= myvar.getTotal() %>

or

<% out.print(myvar.getTotal()); %>

Similarly, we can set a value in the JSP with this syntax:

<jsp:setProperty name="myvar" property="total" value="1234" />

which will do, in effect, the following:

<% myvar.setTotal("1234"); %>

So this would hardly seem worth it, but there are other syntax constructs that make this much more powerful. Remember that we're working with Web-based stuff, with a JSP that will be invoked via a URL. That URL may have parameters on it, and we can map those parameters onto a bean's properties—that is, connect the parameters to setters for a given bean. We replace the value attribute with a parameter attribute, for example:

<jsp:setProperty name="myvar" property="total" parameter="newtot" />

which works the same as:

<% myvar.setTotal ( request.getParameter("newtot") ); %>

We can take that one step further and map all the parameters that arrive in the URL to setters in one step:

<jsp:setProperty name="myvar" parameter="*" />

So if you design your JSP and your HTML well, you can get a lot done automatically for you. One other thing going on behind the scenes that we've glossed over is the type of the argument to the setter. The parameters all come in as Strings. However, if your setter's type is a Java primitive, it will automatically convert to that type for you, instead of just passing you Strings.

One final twist on using beans is the duration of the bean and its values. If you don't specify otherwise (and we have yet to show you syntax to do otherwise) your bean will be around for the duration of the request, at which time it will be available to be garbage-collected. Any values in the bean will not be there on the next visit to that URL (i.e., the next call to that servlet).

Here is the syntax to make that bean last longer:

<jsp:useBean id="myvar" class="net.multitool.servlet.AccountBean"
             scope="session" />

which will make it stay for the duration of the session. You may remember (or you can flip back and look up) how we created and used session variables in the servlet. The same mechanism is at work here, but behind the scenes. You only use the specific syntax in the useBean tag, and it does the rest (getting and storing) for you.

19.3.7 Tag Libraries

Well, we're almost done with JSP, but the one topic that we have yet to cover is huge. It's the trap door, or the way back out, through which JSP can get to lots of other code without the JSP author having to write it. Tag libraries are specially packaged libraries of Java code that can be invoked from within the JSP. Just like the useBean, they can do a lot of work behind the scenes and just return the results.

There are lots of available libraries, which is one reason for this topic to be so huge. We could spend chapters just describing all the various database access routines, HTML generating routines, and so on available to you. Perhaps the leading tag library is the JSP Standard Tag Library (JSTL).

Here are two of the most common directives used with tag libraries. First is the directive that declares a library to be used:

<%@ taglib prefix="my" uri="http://java.sun.com/jstl/core" %>

You then use the prefix as part of the tag name on subsequent tags that refer to this library. For example, if we had an out directive in our library, we could use my as the prefix, separated by a colon: <my:out ...>.

The second directive we will show is a for loop. The for loop mechanism provided by this library is in some ways simpler than using Java scriptlets. It comes in many forms, including one for explicit numeric values:

<my:forEach var="i" begin="0" end="10" step="2">

This example will loop six times with i taking on the values 0, then 2, then 4, and so on. Another variation of the forEach loop can also make it easy to set up the looping values:

<my:forEach var="stripe" items="red,white,blue">

In this example it will parse the items string into three values: red, white, and blue, assigning each, in turn, to the variable stripe. In fact the items attribute can also store an array, or collection, or iterator from the Java code that you may have declared (or that is implicit from the underlying servlet). The forEach will iterate over those values without you having to code the explicit next() calls or index your way through an array.

The bottom of the loop is delimited by the closing tag:

</my:forEach>

For more information on these and other tags, check out

Beyond the standard library of tags, there are other third-party collections of tags; you can also create your own libraries, called custom tag libraries. While a useful and powerful thing to do if you have a large JSP-based application, such details would expand this book well beyond its scope. If you're interested in this topic, please follow up with some of the excellent references at the end of this chapter.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020