Home > Articles > Programming > Java

This chapter is from the book

Overview of JSP Syntax

Now that we're actually working with JSP, the next step is to get an overview of JSP itself, which means getting an overview of the JSP syntax. After we've gotten the components of JSP syntax down, everything else will fit into that framework. There are four different types of elements you can use in JSP:

  • Scripting elements—This is where your Java goes, as in the scriptlets we've already seen.

  • Comments—Comments are text you add to annotate a JSP document—they're like notes to yourself or other programmers. They're ignored by the Web server, and are only for programmers to read.

  • Directives—Directives are instructions specific to a particular page that let you set how the page is to be processed. For example, you can use a directive to indicate that you want the output of a page to be XML, not HTML.

  • Actions—Actions let you perform some operation, such as including other pages in the current page, or including Java applets, or working with JavaBean components (which you'll see in Day 6). Unlike directives, actions are re-evaluated each time the page is accessed.

Let's take a look at these various types of JSP elements, starting with scripting elements.

Scripting Elements

There are three types of scripting elements in JSP:

  • Scriptlets—Scriptlets can contain Java code. This is the most general of all the scripting elements.

  • Declarations—Declares a variable or a method for use in your code.

  • Expressions—Contains a Java expression that the server evaluates. The result of the expression is inserted into the Web page.

Scriptlets

The most general place for your Java code is in a scriptlet. Scriplets hold Java code fragments, and are enclosed with the tags <% and %>. We've already seen an example of a scriptlet in our first JSP, where we used the Java statement out.println("Hello there!"); to display text in a Web page:

<HTML>
 <HEAD>
  <TITLE>A Web Page</TITLE>
 </HEAD>

 <BODY>
  <% out.println("Hello there!"); %>
 </BODY>
</HTML>

A scriptlet can hold any number of Java statements, declarations, or expressions, making scriptlets the most general of all the JSP scripting elements. Note that they must hold valid Java statements, so you can't include direct HTML in a scriptlet.

Scriptlets are what many JSP programmers think of when they think of JSP. Scriptlets are used to embed Java code in HTML documents, turning them into JSP documents. But besides scriptlets, you can also use declarations and expressions.

Declarations

As you'll see tomorrow, you can store data using variables in Java. For example, here's how you can store our text string Hello there! in a variable of type String:

String msg = "Hello there!";

This declares a new variable named msg that holds the text Hello there!. In Java, you must declare variables before you use them, giving them a name. After you've named a variable, you can refer to it in your code using that name.

There's a special set of tags, <%! and %>, that you can use to declare variables in JSP (you can also declare variables in scriptlets, which is a more common thing to do). Here's an example: In this case, the code declares the variable msg:

<HTML>
 <HEAD>
  <TITLE>A Web Page</TITLE>
 </HEAD>

 <BODY>
  <%! String msg = "Hello there!"; %>
 </BODY>
</HTML>

Now you can use this new variable in a scriptlet; for example, here's how you can display the text in msg in the Web page using the out.println method:

<HTML>
 <HEAD>
  <TITLE>A Web Page</TITLE>
 </HEAD>

 <BODY>
  <%! String msg = "Hello there!"; %>
  <% out.println(msg); %>
 </BODY>
</HTML>

That's what the process looks like in overview; you'll get all the details on declaring and using variables in Day 2.

Expressions

Expressions are any Java code fragment that can be evaluated to yield a value. For example, the expression 2 + 2 yields a value of 4, the expression 44 - 10 yields 34, and so on. In JSP, you can surround a Java expression in the tags <%= and %>. The expression's value is inserted into the Web page as text by the server.

You can even use a variable as an expression—when such an expression is evaluated, it yields the value of the variable. For example, if we had stored our string Hello there! in a variable named msg, we can insert that string into the Web page simply by using the variable as an expression this way:

<HTML>
 <HEAD>
  <TITLE>A Web Page</TITLE>
 </HEAD>

 <BODY>
  <%! String msg = "Hello there!"; %>
  <%= msg %>
 </BODY>
</HTML>

Expressions like this are similar to scriptlets, because you can place Java code in them, but they have to be able to result in a single value when they're evaluated.

Expressions like this are useful for shorter JSP pages, but note that you don't have to use them to insert text into a Web page—you can use methods like out.println in scriptlets instead.

Comments

You can use JSP comments to document what's going on in a JSP page; they act like notes to you or other programmers. Comments are purely for the benefit of the programmers that work on the page, because the server will strip them out before sending the page back to the browser. You enclose the text in a comment between the tags <%-- and --%>.

Here's an example; in this case, the code includes the comment Display the message now. to this JSP example:

<HTML>
 <HEAD>
  <TITLE>A Web Page</TITLE>
 </HEAD>

 <BODY>
  <%-- Display the message now. --%>
  <% out.println("Hello there!"); %>
 </BODY>
</HTML>

This comment lets you and other programmers know what's going on in your JSP. You can add as many comments to a JSP as you like—they're entirely for the benefit of programmers, and will all be stripped out before the page is sent back to the browser.

Directives

JSP directives let you give directions to the server on how a page should be processed. There are three directives in JSP; we'll see them throughout the book, but here's an overview:

  • page—This directive lets you configure an entire JSP page, such as whether its output is HTML or XML. You'll see more on this directive in Day 6.

  • include—This directive lets you include another page or resource in a JSP page.

  • taglib—This directive lets you use a set of custom JSP tags as defined in a tag library. More on taglibs is coming up in Day 9, "Using Custom JSP Tags," and Day 10, Creating Custom Tags."

The page directive is going to be a useful one for us as we work with Java. You can use this directive to configure the page you're working on. Like other directives, you use the special tags <%@ and %> with this directive; to create a page directive, you also include the keyword page like this: <%@ page ... %>.

Here's an example to show what the page directive can do for us. In this case, the code wants to indicate that if there's an error in the current page, the server should send an error page named error.jsp back to the browser; that we're programming in Java; that the output of the current page should be XML (not HTML, which is the default—more on XML in Day 18, "Using XML and XSLT in JSP"); and that we want to import the java.sql package so that our code can work with SQL databases. You'll see more on importing Java packages when we start working with Java in depth—Java is divided into many sections called packages, and to use a particular section's functionality, you must import the corresponding package, which makes it accessible to your code.

You can do all that with attributes of a single page directive. In JSP, attributes work just as they do in HTML—they're part of an element's opening tag, and have the form attribute=value. Here's how you can use the errorPage, language, contentType, and import attributes of the page directive to configure the page as you want (note that the page directive comes at the very beginning of the page):

<%@ page errorPage="error.jsp" language="java"
  contentType="application/xml" import="java.sql.*" %>
<HTML>
  <HEAD>
    .
    .
    .

As you can already see, the page directive is going to give us a lot of programming power.

The include directive, which looks like <%@ page ... %>, lets you include another page in the current page. When you include a page at a particular point, that page's entire contents are simply inserted at that point.

The taglib directive (which looks like this: <%@ taglib ... %>) specifies a library of custom JSP tags (see Days 9 and 10) that you want to use in the current page. Tag libraries let you define your own JSP tags. We're going to see how to use this directive later, so we won't go into the details now.

NOTE

There are rumors that scriptlets are going to be phased out in JSP 2.0 and tag libraries will be used instead, so it's a good idea to make sure you know what's going on with tag libraries in Days 9 and 10.

Actions

JSP also includes actions. As their name implies, actions let you perform some action. Unlike directives, actions are re-evaluated each time the page is accessed.

There are two types of actions: custom and standard. Custom actions are actions you create yourself, and standard actions come built into JSP. Here are the standard actions in overview:

  • <jsp:forward>—Forwards the browser request for a new Web page to an HTML file, JSP page, or servlet. In this way, you can delegate how your Web applications respond to the browser.

  • <jsp:include>— Includes a file or Web component. Note that <jsp:include> is different than the include directive because it re-evaluates the included file every time the page is accessed, whereas the include directive does not.

  • <jsp:plugin>— Lets you execute applets or JavaBeans with a plug-in. If the browser doesn't have the required plug-in module, it will display a dialog box asking you to download it. We'll see this one in Day 13.

  • <jsp:getProperty>, <jsp:setProperty>, and <jsp:useBean>—You use these actions with JavaBean components, as you'll see in Day 6.

We'll get all the details on these standard actions when we put them to work in the coming days. And that's it—that completes our overview of JSP syntax. Now we've got the foundation we'll need to move on to Day 2.

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