Head First Servlets and JSP 2nd Edition

Head First Servlets and JSP™ Second Edition by Bryan Basham, Kathy Sierra, and Bert Bates Copyright © 2008 O’Reilly Media, Inc. All rights reserved. P...

79 downloads 931 Views 64MB Size

Head First Servlets and JSP™ Second Edition

by Bryan Basham, Kathy Sierra, and Bert Bates Copyright © 2008 O’Reilly Media, Inc. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly Media books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (safari.oreilly.com). For more information, contact our corporate/institutional sales department: (800) 998-9938 or [email protected]

Series Creators:

Kathy Sierra, Bert Bates

Series Editor:

Brett D. McLaughlin

Design Editor:

Louise Barr

Cover Designers:

Edie Freedman, Steve Fehler, Louise Barr

Production Editor:

Sanders Kleinfeld

Indexer:

Julie Hawks

Interior Decorators:

Kathy Sierra and Bert Bates

Servlet Wrangler:

Bryan Basham

Assistant to the Front Controller:

Bert Bates

Printing History: August 2004: First Edition. March 2008: Second Edition. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. The Head First series designations, Head First Servlets and JSP™, Second Edition, and related trade dress are trademarks of O’Reilly Media, Inc. Java and all Java-based trademarks and logos are trademarks or registered trademarks of Sun Microsystems, Inc., in the United States and other countries. O’Reilly Media, Inc. is independent of Sun Microsystems. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and the author assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein. In other words, if you use anything in Head First Servlets & JSP™ to, say, run a nuclear power plant or air traffic control system, you’re on your own. Readers of this book should be advised that the authors hope you remember them, should you create a huge, successful dotcom as a result of reading this book. We’ll take stock options, beer, or dark chocolate ISBN: 978-0-596-51668-0 [M]

table of contents

Table of Contents (Summary) Intro

xix

1



Why use Servlets & JSPs: an introduction

1

2

Web App Architecture: high-level overview

37

3

Mini MVC Tutorial: hands-on MVC

67

4

Being a Servlet: request AND response

93

5

Being a Web App: attributes and listeners

147

6

Conversational state: session management

223

7

Being a JSP: using JSP

281

8

Script-free pages: scriptless JSP

343

9

Custom tags are powerful: using JSTL

439

10

When even JSTL is not enough: custom tag development

499

11

Deploying your web app: web app deployment

601

12

Keep it secret, keep it safe: web app security

649

13

The Power of Filters: wrappers and filters

701

14

Enterprise design patterns: patterns and struts

737

A

Appendix A: Final Mock Exam

791

i

Index

865

Table of Contents (the real thing)

i

Intro Your brain on Servlets.  Here you are trying to learn something, while here your brain is doing you a favor by making sure the learning doesn’t stick. Your brain’s thinking, “Better leave room for more important things, like which wild animals to avoid and whether naked snowboarding is a bad idea.” So how do you trick your brain into thinking that your life depends on knowing Servlets? Who is this book for?

xx

We know what your brain is thinking

xxi

Metacognition

xxiii

Bend your brain into submission

xv

What you need for this book

xxvi

Passing the certification exam

xxviii

Technical reviewers

xxx

Acknowledgments

xxxi

ix

table of contents

1

Why use Servlets & JSPs Web applications are hot. How many GUI apps do you know that are used by millions of users worldwide? As a web app developer, you can free yourself from the grip of deployment problems all standalone apps have, and deliver your app to anyone with a browser. But you need servlets and JSPs. Because plain old static HTML pages are so, well, 1999. Learn to move from web site to web app.

2

Exam objectives

2

What web servers and clients do, and how they talk?

4

Two-minute guide to HTML

7

What is the HTTP protocol?

10

Anatomy of HTTP GET and POST requests and HTTP responses

16

Locating web pages using URLs

20

Web servers, static web pages, and CGI

24

Servlets Demystified: write, deploy, and run a servlet

30

JSP is what happened when somebody introduced Java to HTML

34

Web app architecture Servlets need help. When a request comes in, somebody has to instantiate the servlet or at least allocate a thread to handle the request. Somebody has to call the servlet’s doPost() or doGet() method. Somebody has to get the request and the response to the servlet. Somebody has to manage the life, death, and resources of the servlet. In this chapter, we’ll look at the Container, and we’ll take a first look at the MVC pattern.

x

Exam Objectives

38

What is a Container and what does it give you?

39

How it looks in code (and what makes a servlet)

44

Naming servlets and mapping them to URLs using the DD

46

Story: Bob Builds a Matchmaking Site ( and MVC intro)

50

A Model-View-Controller (MVC) overview and example

54

A “working” Deployment Descriptor (DD)

64

How J2EE fits into all this

65

3

table of contents

Mini MVC tutorial Create and deploy an MVC web app. It’s time to get your hands dirty writing an HTML form, a servlet controller, a model (plain old Java class), an XML deployment descriptor, and a JSP view. Time to build it, deploy it, and test it. But first, you need to set up your development environment. Next, you need to set up your deployment environment following the servlet and JSP specs and Tomcat requirements. True, this is a small app... but there’s almost NO app that’s too small to use MVC. Exam Objectives

4

68

Let’s build an MVC application; the first design

69

Create the development and deployment environments

72

Create and test the HTML for the initial form page

75

Create the Deployment Descriptor (DD)

77

Create, compile, deploy, and test the controller servlet

80

Design, build, and test the model component

82

Enhance the controller to call the model

83

Create and deploy the view component (it’s a JSP)

87

Enhance the controller servlet to call the JSP

88

Being a Servlet Servlets need help. When a request A servlet’s job is to take a client’s request and send back a response. The request might be simple: “get me the Welcome page.” Or it might be complex: “Complete my shopping cart check-out.” The request carries crucial data, and your servlet code has to know how to find it and how to use it. And your servlet code has to know how to send a response. Or not... Exam Objectives A servlet’s life in the Container Servlet initialization and threads A Servlet’s REAL job is to handle GET and POST requests. The story of the non-idempotent request What determines whether you get a GET or POST request? Sending and using parameter(s) So that’s the Request... now let’s see the Response You can set response headers, you can add response headers Servlet redirect vs. request dispatcher Review: HttpServletResponse

94 95 101 105 112 117 119 126 133 136 140

xi

table of contents

5

Being a web app No servlet stands alone. In today’s modern web app, many components work together to accomplish a goal. You have models, controllers, and views. You have parameters and attributes. You have helper classes. But how do you tie the pieces together? How do you let components share information? How do you hide information? How do you make information thread-safe? Your job may depend on the answers.

xii

Exam Objectives

148

Init Parameters and ServletConfig to the rescue

149

How can a JSP get servlet init parameters?

155

Context init parameters to the rescue

157

Comparing ServletConfig with ServletContext

159

She wants a ServletContextListener

166

Tutorial: a simple ServletContextListener

168

Compile, deploy, and test your listener

176

The full story, a ServletContextListener review

178

Eight Listeners: they’re not just for context events...

180

What, exactly, is an attribute?

185

The Attribute API and the dark side of attributes

189

Context scope isn’t thread-safe!

192

The problem in slow motion...

193

Trying out Synchronization

195

Are Session attributes thread-safe?

198

The SingleThreadModel

201

Only Request attributes and local variables are thread-safe!

204

Request attributes and Request dispatching

205

6

table of contents

Conversational state Web servers have no short-term memory. As soon as they send you a response, they forget who you are. The next time you make a request, they don’t recognize you. They don’t remember what you’ve requested in the past, and they don’t remember what they’ve sent you in response. Nothing. But sometimes you need to keep conversational state with the client across multiple requests. A shopping cart wouldn’t work if the client had to make all his choices and then checkout in a single request. Exam Objectives

7

224

It’s supposed to be a conversation, (how sessions work)

226

Session IDs, cookies, and other session basics

231

URL rewriting: something to fall back on

237

When sessions get stale; getting rid of bad sessions

241

Can I use cookies for other things, or are they only for sessions?

250

Key milestones for an HttpSession

254

Don’t forget about HttpSessionBindingListener

256

Session migration

257

Listener examples

261

Being a JSP A JSP becomes a servlet. A servlet that you don’t create. The Container looks at your JSP, translates it into Java source code, and compiles it into a full-fledged Java servlet class. But you’ve got to know what happens when the code you write in the JSP is turned into Java code. You can write Java code in your JSP, but should you? And if not Java code, what do you write? How does it translate into Java code? We’ll look at six different kinds of JSP elements—each with its own purpose and, yes, unique syntax. You’ll learn how, why, and what to write in your JSP. And you’ll learn what not to write. Exam Objectives

282

Create a simple JSP using “out” and a page directive

283

JSP expressions, variables, and declarations

288

Time to see a JSP-generated servlet

296

The out variable isn’t the only implicit object...

298

The Lifecycle and initialization of a JSP

306

While we’re on the subject... let’s talk more about the three directives

314

Scriptlets considered harmful? Here’s EL

317

But wait... we haven’t seen: actions

323

xiii

table of contents

8

Script-free pages Lose the scripting. Do your web page designers really have to know Java? Do they expect server-side Java programmers to be, say, graphic designers? And even if it’s just you on the team, do you really want a pile of bits and pieces of Java code in your JSPs? Can you say, “maintenance nightmare”? Writing scriptless pages is not just possible, it’s become much easier and more flexible with the new JSP 2.0 spec, thanks to the new Expression Language (EL). Patterned after JavaScript and XPATH, web designers feel right at home with EL, and you’ll like it too (once you get used to it). But there are some traps... EL looks like Java, but isn’t. Sometimes EL behaves differently than if you used the same syntax in Java, so pay attention!

xiv

Exam Objectives

344

When attributes are beans

345

Standard actions: useBean, getProperty, setProperty

349

Can you make polymorphic bean references?

354

The param attribute to the rescue

360

Converting properties

363

Expression Language (EL) saves the day!

368

Using the dot (.) operator to access properties and map values

370

The [] gives you more options (Lists, arrays...)

372

More dot and [ ] operator details

376

The EL implicit objects

385

EL functions, and handling “null”

392

Reusable template pieces—two kinds of “include”

402

The standard action

416

She doesn’t know about JSTL tags (a preview)

417

Reviewing standard actions and include

417

table of contents

9

Custom tags are powerful Sometimes you need more than EL or standard actions. What if you want to loop through the data in an array, and display one item per row in an HTML table? You know you could write that in two seconds using a for loop in a scriptlet. But you’re trying to get away from scripting. No problem. When EL and standard actions aren’t enough, you can use custom tags. They’re as easy to use in a JSP as standard actions. Even better, someone’s already written a pile of the ones you’re most likely to need, and bundled them into the JSP Standard Tag Library (JSTL). In this chapter we’ll learn to use custom tags, and in the next chapter we’ll learn to create our own.

http://localhost:8080/testJSP1/Tester.do

Exam Objectives

440

Looping without scripting

446

Conditional control with and

451

Using the and tags

455

With , there are now three ways to include content

460

Customizing the thing you include

462

Doing the same thing with

463

for all your hyperlink needs

465

Make your own error pages

468

The tag. Like try/catch...sort of

472

What if you need a tag that’s NOT in JSTL?

475

Pay attention to

480

What can be in a tag body

482

The tag handler, the TLD, and the JSP

483

The taglib is just a name, not a location

484

When a JSP uses more than one tag library

487

xv

table of contents

10

When even JSTL isn’t enough... Sometimes JSTL and standard actions aren’t enough. When you need something custom, and you don’t want to go back to scripting, you can write your own tag handlers. That way, your page designers can use your tag in their pages, while all the hard work is done behind the scenes in your tag handler class. But there are three different ways to build your own tag handlers, so there’s a lot to learn. Of the three, two were introduced with JSP 2.0 to make your life easier (Simple Tags and Tag Files). Exam Objectives

11

500

Tag Files: like include, only better

502

Where the Container looks for Tag Files

509

Simple tag handlers

513

A Simple tag with a body

514

What if the tag body uses an expression?

519

You still have to know about Classic tag handlers

529

A very small Classic tag handler

531

The Classic lifecycle depends on return values

536

IterationTag lets you repeat the body

537

Default return values from TagSupport

539

The DynamicAttributes interface

556

With BodyTag, you get two new methods

563

What if you have tags that work together?

567

Using the PageContext API for tag handlers

577

Deploying your web app Finally, your web app is ready for prime time. Your pages are polished, your code is tested and tuned, and your deadline was two weeks ago. But where does everything go? So many directories, so many rules. What do you name your directories? What does the client think they’re named? What does the client actually request, and how does the Container know where to look?

xvi

Exam Objectives

602

Key deployment task, what goes where?

603

WAR files

612

How servlet mapping REALLY works

616

Configuring welcome files in the DD

622

Configuring error pages in the DD

626

Configuring servlet initialization in the DD

628

Making an XML-compliant JSP: a JSP Document

629

12

table of contents

Keep it secret, keep it safe Your web app is in danger. Trouble lurks in every corner of the network. You don’t want the Bad Guys listening in to your online store transactions, picking off credit card numbers. You don’t want the Bad Guys convincing your server that they’re actually the Special Customers Who Get Big Discounts. And you don’t want anyone (good OR bad) looking at sensitive employee data. Does Jim in marketing really need to know that Lisa in engineering makes three times as much as he does? Exam Objectives

13

650

The Big 4 in servlet security

653

How to Authenticate in HTTP World

656

Top Ten Reasons to do your security declaratively

659

Who implements security in a web app?

660

Authorization roles and constraints

662

Authentication: four flavors

677

The FOUR authentication types

677

Securing data in transit: HTTPS to the rescue

682

Data confidentiality and integrity sparingly and declaratively

684

The power of filters Filters let you intercept the request. And if you can intercept the request, you can also control the response. And best of all, the servlet remains clueless. It never knows that someone stepped in between the client request and the Container’s invocation of the servlet’s service() method. What does that mean to you? More vacations. Because the time you would have spent rewriting just one of your servlets can be spent instead writing and configuring a filter that has the ability to affect all of your servlets. Want to add user request tracking to every servlet in your app? No problem. Manipulate the output from every servlet in your app? No problem. And you don’t even have to touch the servlet. Exam Objectives

702

Building the request tracking filter

707

A filter’s life cycle

708

Declaring and ordering filters

710

Compressing output with a response-side filter

713

Wrappers rock

719

The real compression filter code

722

Compression wrapper code

724

xvii

table of contents

14

Enterprise design patterns Someone has done this already. If you’re just starting to develop web applications in Java, you’re lucky. You get to exploit the collective wisdom of the tens of thousands of developers who’ve been down that road and got the t-shirt. Using both J2EE-specific and other design patterns, you can can simplify your code and your life. And the most significant design pattern for web apps, MVC, even has a wildly popular framework, Struts, that’ll help you craft a flexible, maintainable servlet Front Controller. You owe it to yourself to take advantage of everyone else’s work so that you can spend more time on the more important things in life...

A

Exam Objectives

738

Hardware and software forces behind patterns

739

Review of softweare design principles...

744

Patterns to support remote model components

745

Overview of JNDI and RMI

747

The Business Delegate is a “go-between”

753

Time for a Transfer Object?

759

Business tier patterns: quick review

761

Our very first pattern revisited... MVC

762

Yes! It’s Struts (and FrontController) in a nutshell

767

Refactoring the Beer app for Struts

770

Review of patterns

778

The final Coffee Cram Mock Exam. This is it. 69 questions. The tone, topics, and difficulty level are all virtually identical to the real exam. We know.

i xviii

Index

Final mock exam

791

Answers

828

865

9

using JSTL

Custom tags are powerful You mean, I spent all this time writing scriptlets for the things I can’t do with EL and standard actions, when I could have used JSTL?

Sometimes you need more than EL or standard actions. What if you want to loop through the data in an array, and display one item per row in an HTML table? You know you could write that in two seconds using a for loop in a scriptlet. But you’re trying to get away from scripting. No problem. When EL and standard actions aren’t enough, you can use custom tags. They’re as easy to use in a JSP as standard actions. Even better, someone’s already written a pile of the ones you’re most likely to need, and bundled them into the JSP Standard Tag Library (JSTL). In this chapter we’ll learn to use custom tags, and in the next chapter we’ll learn to create our own.

this is a new chapter

439

official Sun exam objectives

Building JSP pages using tag libraries

Coverage Notes:

9.1 Describe the syntax and semantics of the ‘taglib’

All of the objectives in this section are covered in this chapter, although some of the content is covered again in the next chapter (Developing Custom Tags).

directive: for a standard tag library, for a library of Tag Files.

9.2 Given a design goal, create the custom tag structure to support that goal.

9.3 Identify the tag syntax and describe the action semantics of the following JSP Standard Tag Library (JSTL v1.1) tags: (a) core tags: out, set, remove, and catch, (b) conditional tags: if, choose, when, and otherwise, (c) iteration tags: forEach, and (d) URL-related: url.

Installing the JSTL 1.1 The JSTL 1.1 is NOT part of the JSP 2.0 specification! Having access to the Servlet and JSP APIs doesn’t mean you have access to JSTL. Before you can use JSTL, you need to put two files, “jstl.jar” and “standard. jar” into the WEB-INF/lib directory of your web app. That means each web app needs a copy. In Tomcat 5, the two files are already in the example applications that ship out-of-the-box with Tomcat, so all you need to do is copy them from one directory and put them into your own app’s WEB-INF/lib directory. Copy the files from the Tomcat examples at: webapps/jsp-examples/WEB-INF/ lib/jstl.jar webapps/jsp-examples/WEB-INF/ lib/standard.jar And place it in your own web app’s WEB-INF/lib directory.

440

chapter 9

using JSTL

There’s got to be a way to iterate through a collection in a JSP...without scripting. I want to show one element per row in a table...

EL and standard actions are limited What happens when you bump into a brick wall? You can go back to scripting, of course—but you know that’s not the path. Developers usually want way more standard actions or—even better—the ability to create their own actions. That’s what custom tags are for. Instead of saying , you want to do something like . And you can. But it’s not that easy to create the support code that goes behind the tag. For the JSP page creator, custom tags are much easier to use than scripting. For the Java programmer, however, building the custom tag handler (the Java code invoked when a JSP uses the tag) is tougher. Fortunately, there’s a standard library of custom tags known as the JSP Standard Tag Library (JSTL 1.1). Given that your JSP shouldn’t be doing a bunch of business logic anyway, you might find that the JSTL (combined with EL) is all you’ll ever need. Still, there could be times when you need something from, say, a custom tag library developed specifically for your company. In this chapter, you’ll learn how to use the core JSTL tags, as well as custom tags from other libraries. In the next chapter, we’ll learn how to actually build the classes that handle calls to the custom tags, so that you can develop your own.

you are here �

441

where’s my html?

The case of the disappearing HTML (reprised) On page 384, you saw how EL sends the raw string of content directly to the response stream:

Tip of the Day:

${pageContent.currentTip}


What we got

What we want

Tip of the Day:
tags make things bold!


This comes out as an “invisible” bolded empty space.

> Remember this? The
Tip of the Day:

tags make things bold!


Rendered as

Rendered as

http://localhost:8080/testJSP1/Tester.do

< is rendered > is rendered as “<”, and as “>”.

http://localhost:8080/testJSP1/Tester.do

Tip of the Day:

Tip of the Day:

tags make things bold!

tags make things bold!

What we need is a way to convert those angle brackets into something the browser will render as angle brackets, and there are two ways to do this. Both use a static Java method that converts HTML special characters into their entity format:

Use an EL function

Use a Java helper method

Tip of the Day:

${fn:convEntity(pageContent.currentTip)}


442

chapter 9

Here’s the helper method to make this one work.

Tip of the Day:

${pageContent.convertedCurrentTip}


public String getConvertedCurrentTip() { return HTML.convEntity(getCurrentTip()); }

using JSTL

There’s a better way: use the tag Whichever approach you use, it’s a bit unclear exactly what’s going on... and you may have to write that helper method for all your servlets. Luckily, there’s a better way. The tag is perfect for the job. Here’s how conversion works:

You can explicitly declare the conversion of XML entities If you know or think you might run into some XML entities that need to be displayed, and not just rendered, you can use the escapeXml attribute on c:out. Setting this to true means that any XML will be converted to something the web browser will render, angle brackets and all:
Tip of the Day:



You can explicitly declare NO conversion of XML entities Sometimes, you want just the opposite behavior. Maybe you’re building a page that takes content, and you want to display that content with HTML formatting. In that case, you can turn off XML conversion:

Your HTML is treated as XHTML, which in turn is XML... so this affects HTML characters, too.

Tip of the Day:



Conversion happens by default The escapeXml attribute defaults to true, so you can leave it out if you want. A c:out tag without an escapeXML attribute is just the same as a c:out tag with escapeXML set to “true.”

This is equivale we had before...nt to what tags are evaluatedany HTML displayed as text , not .

Tip of the Day:



This is actually identical in functionality to this.

you are here �

443

escaping html

there are no

Dumb Questions

Q: A:

Which HTML special characters are converted?

It turns out this conversion is rather simple. There are only five characters that require escaping: <, >, &, and the two quote symbols, single and double ". All of these are converted into the equivalent HTML entities. For example, < becomes <, & becomes &, and so on.

Q:

Character

Character Entity Code

< > & ' "

< > & ' "

Last month my company hired a web consultant to audit our web application. She noticed that we were using EL everywhere to output strings entered by users. She said this was a security risk and recommended we output all user strings using the c:out tag. What gives?

A:

Your consultant was right. The security risk she is referring to is called cross-site hacking or cross-site scripting. The attack is sent from one user to another user’s web browser using your webapp as the delivery mechanism.

User1 “cracker”

The cracker enters a comment field in your webapp, which is stored in the database. The cracker includes viral JavaScript code in the comment. Your webapp

User2 “innocent” The innocent user views the cracker’s comment, but the text the cracker entered also includes JavaScript code that compromises user2’s system!

Q: A:

What happens if value of the EL expression is null?

Good question. You know an EL expression ${evalsToNull} generates an empty string in the response output, and so will . But that’s not the end of the story with c:out. The c:out tag is smart, and it recognizes when the value is null and can perform a special action. That action is to provide a default value...

444

chapter 9

to render Using the c:out tas gprevents the text of user g of this form cross-site hackin <script> tags by displaying the in user2’s web and the JS code ents the JS browser. This previnterpreted by code from being the attack the browser, foils from user1.

using JSTL

Null values are rendered as blank text Suppose you have a page that welcomes the user by saying “Hello .” But lately, users haven’t been logging in, and the output looks pretty odd:

EL prints nothing if user is null Hello ${user}.

Renders as

Hello .

Since ${user} and <% evaluate to null, you ge=tuser %> space between “Hello” an an empty Pretty strange looking... d the “.”

A JSP expression tag prints nothing if user is null Hello <%= user %>.

Renders as

Hello .

Set a default value with the default attribute Suppose you want to show these anonymous users a message that says, “Hello guest.” This is a perfect place to use a default value with the c:out tag. Just add a default attribute, and provide the value you want to print if your expression evaluates to null:

provides a default attribute

This value is output if the value attribute evaluates to null.

Hello .

Renders as

Now the default value is inserted... perfect.

Hello guest.

Or you can do it this way: Hello guest you are here �

445

the tag

Looping without scripting Imagine you want something that loops over a collection (say, an array of catalog items), pulls out one element at a time, and prints that element in a dynamically-generated table row. You can’t possibly hard-code the complete table—you have no idea how many rows there will be at runtime, and of course you don’t know the values in the collection. The tag is the answer. This does require a very slight knowledge of HTML tables, but we’ve included notes here for those who aren’t familiar with the topic. By the way, on the exam you are expected to know how to use with tables.

Servlet code ... String[] movieList = {“Amelie”, “Return of the King”, “Mean Girls”}; request.setAttribute(“movieList”, movieList); ... Mak

What you want

e a St set the arrring[] of movie names, ay as a requ est attribuatnd e.

http://localhost:8080/testJSP1/Tester.do

Movie list: Amelie Return of the King Mean Girls

In a JSP, with scripting <% String[] items = (String[]) request.getAttribute(“movieList”); String var=null; for (int i = 0; i < items.length; i++) { var = items[i]; %> <% } %>
<%= var %>


446

chapter 9

using JSTL

The tag from the JSTL is perfect for this—it gives you a simple way to iterate over arrays and collections. JSP code

this taglib (We’ll talk aboutin the chapter.) directive later

<%@ taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core” %> Movie list:





he e entire array (t Loops through thibute) and prints each “movieList” attrw row. (This table has element in a ne per row.) just one column

${movie}


Crash refresher on HTML tables

Table Row. stands for Table Data.





























stands for

data for this cell data for this cell data for this cell
data for this cell data for this cell data for this cell
data for this cell data for this cell data for this cell
Tables are pretty straightforward. They’ve got cells, arranged into rows and columns, and the data goes inside the cells. The trick is telling the table how many rows and columns you want. Rows are defined with the (Table Row) tag, and columns are defined with the (Table Data) tag. The number of rows comes from the number of tags, and the number of columns comes from the number of tags you put inside the tags.

Data to print/display goes only inside the tags! you are here �

447

the tag

Deconstructing The tag maps nicely into a for loop—the tag repeats the body of the tag for each element in the collection (and we use “collection” here to mean either an array or Collection or Map or comma-delimited String). The key feature is that the tag assigns each element in the collection to the variable you declare with the var attribute.

The tag

the ch ELEMENT ination. ea s ld ho at th le The variab value changes with each iter collection. Its



The actual thin (array, Collectiogn,to loop over comma-delimited Map, or a String).

${movie}


String[] items = (String[]) request.getAttribute(“movieList”); for (int i = 0; i < items.length; i++) { String movie = items[i]; out.println(movie); }

Getting a loop counter with the optional varStatus attribute

varStatus mak that holds an inessta new variable servlet.jsp.jstl.cor ance of javax. e.LoopTagStatus.

Count: ${movieLoopCount.count}
${movie}



448

chapter 9

Helpfully, the LoopTagStatus class has a count property that gives you the current value of the iteration counter. (Like the “i” in a for loop.)

http://localhost:8080/testJSP1/Tester.do

Count: 1 Amelie Count: 2 Return of the King Count: 3 Mean Girls

using JSTL

You can even nest tags What if you have something like a collection of collections? An array of arrays? You can nest tags for more complex table structures. In this example, we put String arrays into an ArrayList, then make the ArrayList a request attribute. The JSP has to loop through the ArrayList to get each String array, then loop through each String array to print the actual elements of the array. Servlet code String[] movies1 = {“Matrix Revolutions”, “Kill Bill”, “Boondock Saints”}; String[] movies2 = {“Amelie”, “Return of the King”, “Mean Girls”}; java.util.List movieList = new java.util.ArrayList(); movieList.add(movies1); movieList.add(movies2); request.setAttribute(“movies”, movieList);

JSP code

est attribute The ArrayList requ



outer loop



inner loop

One of the Str that was assigneding arrays outer loop’s “var” to the at

tribute.

${movie}
http://localhost:8080/testJSP1/Tester.do

From the first S

tring[]

From the second String[]

Matrix Revolutions Kill Bill Boondock Saints Amelie Return of the King Mean Girls

you are here �

449

the tag

there are no

Dumb Questions

Q:

How did you know that the “varStatus” attribute was an instance of whatever that was, and how did you know that it has a “count” property?

A:

Ahhhh... we looked it up.

It’s all there in the JSTL 1.1 spec. If you don’t have the spec already, go download it NOW (the intro of this book tells you where to get the specs covered on the exam). It is THE reference for all the tags in the JSTL, and tells you all the possible attributes, whether they’re optional or required, the attribute type, and any other details on how you use the tag. Everything you need to know about these tags (for the exam) is in this chapter. But some of the tags have a few more options than we cover here, so you might want to have a look in the spec.

Q:

Since you know more than you’re telling about this tag... does it give you a way to change the iteration steps? In a real Java for loop, I don’t have to do i++, I can do i +=3, for example, to get every third element instead of every element... Not a problem. The tag has optional attributes for begin, end (in case you want to iterate over a subset of the collection), and step if you want to skip over some elements.

Is the “c” in a required prefix?

> items=”${fooList}”
${foo}

is oo” variable NO!! The “fpe ! out of sco

scope as being just like It might help to think of tag a code. An example is the Jav block scope in plain old love: for loop you all know and { items.length; i++) for (int i = 0; i < x + i;

Well, some prefix is required, of course; all tags and EL functions must have a prefix to give the Container the namespace for that tag or function name. But you don’t HAVE to name the prefix “c”. It’s just the standard convention for the set of tags in JSTL known as “core”. We recommend using something other than “c” as a prefix, whenever you want to totally confuse the people you work with.

450

pe this isn’t a full-fledged sco That’s right, tag scope. No r— fou ibutes like the other to which you can bind attr application. Tag scope and n, sio ses page, request, a iable was declared INSIDE simply means that the var loop. s. at that means in Java term And you already know wh with set le iab var a s, tag er You’ll see that for most oth ible to whatever scope you a “var” attribute will be vis OR, optional “scope” attribute), specifically set (using an pe. sco e pag the variable will default to iable e that tries to use the var So don’t be fooled by cod the end of somewhere BELOW the ! tag y bod > ach forE


A:

Q: A:

Watch it!

The “var” variable is tag! scoped to ONLY the

chapter 9

} doSomething(i);

variable NO!! The “ i”ope ! is out of sc

using JSTL

Doing a conditional include with Imagine you have a page where users can view comments from other users. And imagine that members can also post comments, but non-member guests cannot. You want everyone to get the same page, but you want members to “see” more things on the page. You want a conditional and of course, you don’t want to do it with scripting! What members see:

What NON-members see:

http://localhost:8080/testJSP1/Tester.do

http://localhost:8080/testJSP1/Tester.do

d...” parts d A “ e h t t a an We don’t wif the client is NOT r a e to app member.

JSP code <%@ taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core” %> re set Member Comments
a servlet somewe,hebased on e um ss A
${commentList}
ype attribut

the userT n information. the user’s logi



Included page (“inputComments.jsp”)

Yes, those are SINGLE quotes around ‘member’. Don’t forget that you can use EITHER double or single quotes in your tags and EL.

Add your comment:



you are here �

451

the tag

But what if you need an else ? What if you want to do one thing if the condition is true, and a different thing if the condition is false? In other words, what if we want to show either one thing or the other, but nobody will see both? The on the previous page worked fine because the logic was: everybody sees the first part, and then if the test condition is true, show a little extra. But now imagine this scenario: you have a car sales web site, and you want to customize the headline that shows up on each page, based on a user attribute set up earlier in the session. Most of the page is the same regardless of the user, but each user sees a customized headline—one that best fits the user’s personal motivation for buying. (We are, after all, trying to sell him a car and become obscenely wealthy.) At the beginning of the session, a form asks the user to choose what’s most important... At the beginning of the session: http://localhost:8080/testJSP1/Tester.do

When buying a car, what is most important to you?

Somewhere later in the session: http://localhost:8080/testJSP1/Tester.do

Now you can stop even if you do drive insanely fast. The Brakes Our advanced anti-lock brake system (ABS) is engineered to give you the ability to steer even as you’re stopping. We have the best speed sensors of any car this size.

452

chapter 9

age istle, p s ’ r e s it The uomized a lerests... t t s cu it his in to f

Imagine a web site for a car company. The first page asks the user what he feels is most important. Just like a good salesman, the pages that talk about features of the car will customize the presentation based on the user’s preference, so that each feature of the car looks like it was made with HIS personal needs in mind...

using JSTL

The tag won’t work for this There’s no way to do exactly what we want using the tag, because it doesn’t have an “else”. We can almost do it, using something like: JSP using , but it doesn’t work right... Now you can stop even if you do drive insanely fast.. Our brakes won’t lock up no matter how bad a driver you are. Lost your tech job? No problem--you won’t have to service these brakes for at least three years. any of these?

ref doesn’t match But what happens if userP the default headline? There’s no way to specify



s set Assume “userPref” inwathe session. somewhere earlier

<% String pref = (String) session.getAttribute(“userPref”); if (pref.equals(“performance”)) { out.println(“Now you can stop even if you do drive insanely fast.”); } else if (pref.equals(“safety”)) { out.println(“Our brakes won’t lock up, no matter how bad a driver you are. “); } else if (pref.equals(“maintenance”)) { out.println(“ Lost your tech job? No problem--you won’t have to service these brakes for at least three years.”); } else { // userPref doesn’t match those, so print the default headline out.println(“Our brakes are the best.”); } %>

The Brakes
Our advanced anti-lock brake system (ABS) is engineered to give you the ability to steer even as you’re stopping. We have the best speed sensors of any car this size.
*Yes, we agree with you—there’s nearly always a better approach than chained if tests. But you’re just gonna have to suspend disbelief long enough to learn how this all works.... you are here �

453

the tag I will CHOOSE you WHEN you are ready to give

up your obsession with Pilates. OTHERWISE, I’ll have to go with Kenny for the synchronized swim team.

The tag and its partners and

r bodies of these foilul run. E N O n a h t No more he ) w (including t t-itch statemen sw a e k li t o ( It’s n fall-through .) there’s no

Now you can stop even if you do drive insanely fast. Our brakes will never lock up, no matter how bad a driver you are. Lost your tech job? No problem--you won’t have to service these brakes for at least three years. Our brakes are the best.

If none of the runs >astea sts are true, default.



454

chapter 9

Note: the tag is NOT required to have a tag.

using JSTL

The tag... so much cooler than The tag can do only one thing—set the property of a bean. But what if you want to set a value in a Map? What if you want to make a new entry in a Map? Or what if you simply want to create a new request-scoped attribute? You get all that with , but you have to learn a few simple rules. Set comes in two flavors: var and target. The var version is for setting attribute variables, the target version is for setting bean properties or Map values. Each of the two flavors comes in two variations: with or without a body. The body is just another way to put in the value.

Setting an attribute variable var with 1

With NO body

evel”, tribute named “usenorLt null). at ed op sc nio ss se a If there’s NOT e (assuming the value attribute is this tag creates on



The scope is optional; va r is You MUST specify a value required. , have a choice between pu but you tting in a value attribute or putting th in the tag body (see #2 e value below).

ring...

value



2

WITH a body

St e to be a v a h ’t n s e do

If ${person.dog} evaluates to a Dog object, then “Fido” is of type Dog.

re Remember, no slasha hebody. s ha g when the ta >

d and used The body is evaluate riable. as the value of the va

will be s to null, the variable If the value evaluate ht, removed. REMOVED! That’s rig tag or using the value at(either in the body of the to null (meaning Imagine that for the value If ${person.dog} evaluates }. dog on. ers ${p le use you tribute), l, then if there IS a variab son’s dog property is nul per or , cify son spe per ’t no don is re you the oved! (If o”, that attribute will be rem attribute with a name “Fid .). This happens even if etc t, ues req n the e, pag at g kin loo rt sta will it a scope, Duck, or a Broccoli. inally set as a String, or a orig s wa te ibu attr o” “Fid the

you are here �

455

the tag

Using with beans and Maps This flavor of (with its two variations—with and without a body) works for only two things: bean properties and Map values. That’s it. You can’t use it to add things to lists or arrays. It’s simple—you give it the object (a bean or Map), the property/key name, and the value.

Setting a target property or value with

lue bean, set the .va a is t ge ar t If y “dogName” of the propert

With NO body

1



target must NOT be

WITH a body

2

null!!

If target is a Map, value of a key namedse“dt the ogName”. “id” name Don’t put thbeute here ! of the attri

${foo.name} The body can be a

for No slash... watch . this on the exam

String or expre

ssion.

! You don’t aluate to the OBJECT The “target” must ev Map attribute! or ” name of the bean “id ing Str the in e typ like it ” attribute in the tag seems the tag, the “target In er . oth cha got the e in te hug a ibu is attr s r” Thi the “va the . Even attribute. ped sco the of e should work just like “id” in nam the s String literal that represent version of takes a ”! get “tar h wit y wa represents the name BUT... it doesn’t work this e in the String literal that typ T NO do you te, ibu , the “target” attribute With the “target” attr to the page, scope, etc. No nd bou s wa a te ibu attr the under which ans an EL expression or the REAL THING. That me to es olv >. res ute t tha ttrib ue p:a val ), or something we hav scripting expression (<%=

456

chapter 9

using JSTL

Key points and gotchas with Yes, is easy to use, but there are a few deal-breakers you have to remember...

é

You can never have BOTH the “var” and “target” attributes in a .

é

“Scope” is optional, but if you don’t use it the default is page scope.

é

If the “value” is null, the attribute named by “var” will be removed!

é

If the attribute named by “var” does not exist, it’ll be created, but only if “value” is not null.

é

If the “target” expression is null, the Container throws an exception.

The “target” is for putting in an expression that

é

resolves to the Real Object. If you put in a String literal that represents the “id” name of the bean or Map, it won’t work. In other words, “target” is not for the attribute name of the bean or Map—it’s for the actual attribute object.

é

If the “target” expression is not a Map or a bean, the Container throws an exception.

é

If the “target” expression is a bean, but the bean does not have a property that matches “property”, the Container throws an exception. Remember that the EL expression ${bean.notAProperty} will also throw an exception.

there are no

Dumb Questions

Q:

Why would I use the body version instead of the no-body version? It looks like they both do exactly the same thing.

A:

That’s because they DO... do the same thing. The body version is just for convenience when you want more room for the value. It might be a long and complex expression, for example, and putting it in the body makes it easier to read.

Q:

If I don’t specify a scope, does that mean it will find attributes that are ONLY within page scope, or does it do a search beginning with page scope?

A:

If you don’t use the optional “scope” attribute in the tag, then the tag will only look in the page scope space. Sorry, you will just have to know exactly which scope you are dealing with.

Q:

Why is the word “attribute” so overloaded? It means both “the things that go inside tags” and “the things that are bound to objects in one of the four scopes.” So you end up with an attribute of a tag whose value is an attribute of the page and...

A:

We hear you. But that’s what they’re called. Once again, nobody asked US. We would have called the bound objects something like, oh, “bound objects”.

you are here �

457

the tag

I can’t believe you have to use to remove an attribute. That feels wrong.

just makes sense We agree with Dick—using a set to remove something feels wrong. (But remember, set does a remove only when you pass in a null value.) The tag is intuitive and simple:

<%@ taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core” %>

The var att MUST be a riStbute literal ! It can’tring an expression !! be

userStatus: ${userStatus}


userStatus is now: ${userStatus}

The scope is tional, but if yo it out then top u leave h e from ALL scop attribute is removed es.

http://localhost:8080/testJSP1/Tester.do

userStatus: Brilliant userStatus is now:

458

chapter 9

The value of us nothing prints erStatus was removed, so is used AFTERwhen the EL expression the remove.

using JSTL

Sharpen your pencil

Test your Tag memory If you’re studying for the exam, don’t skip this one. The answers are at the end of the chapter.

1

Fill in the name of the optional attribute.

2

=”foo”

>

Fill in the missing attribute name. Maybe you should just walk...

3

Fill in the missing attribute name.
4

=”foo” />

Fill in the missing tag names (two different tag types), and the missing attribute name. Now you can stop even if you do drive insanely fast.
> Our brakes are the best.
you are here �

459

the tag

With , there are now THREE ways to include content So far, we’ve used two different ways to add content from another resource into a JSP. But there’s yet another way, using JSTL. 1

The include directive <%@ include file=”Header.html” %> Static: adds the content from the value of the file attribute to the current page at translation time.

2

The standard action Dynamic: adds the content from the value of the page attribute to the current page at request time.

3

The JSTL tag

o includes, m w t r e h t o e Unlike th port> url can be fro the
Dynamic: adds the content from the value of the URL attribute to the current page, at request time. It works a lot like , but it’s more powerful and flexible.

Do NOT confuse (a type of include) with the “import” attribute of the page directive (a way to put a Java import statement in the generated servlet).

t attribute names! They all have differen clude” vs. “import”) (And watch out for “in sa r resource into your JSP use luding content from anothe inc and for e, ms pag nis s cha use me e de> clu Each of the thre s file, the tag s originally intended for sta wa e ctiv t ten dire con The ic e. am thre to memorize all was intended more for dyn a “file”. The te for headers. In other words, to reflect that. The attribu ge” “pa te ibu attr e the ed nam y “includes” can’t go outsid coming from JSPs, so the L! Remember, the first two UR a it— e giv you at wh is named for exactly can. the current Container, but

460

chapter 9

using JSTL

can reach OUTSIDE the web app With or the include directive, you can include only pages that are part of the current web app. But now with , you have the option to pull in content from outside the Container. This simple example shows a JSP on Server A importing the contents of a URL on Server B. At request time, the HTML chunk in the imported file is added to the JSP. The imported chunk uses a reference to an image that is also on Server B. Server A, the JSP doing the import

A

The JSP <%@ taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core” %>
This is my horse.

Server B, the imported content

(Don’t forget: as with other include mechanisms, thea thing you import should be an HTML fragment and NOTdy> tags.) complete page with opening and closing
The imported file

B



The response http://localhost:8080/testJSP1/Tester.do

ming The horse is coetely from a compl server different web that than the pagetext. This is my horse. contains the

“horse.html” and “horse.gif” are both on Server B, a completel different web server from they one with the JSP.

you are here �

461

the tag

Customizing the thing you include Remember in the previous chapter when we did a to put in the layout header (a graphic with some text), but we wanted to customize the subtitle used in the header? We used to make that happen... 1

The JSP with the


Welcome to our Web Services Support Group.

Contact us at: ${initParam.mainEmail}

2

The included file (“Header.jsp”)


${param.subTitle}


http://localhost:8080/tests/Contact.jsp

2

We take the sting out of SOAP. Welcome to our Web Services Support Group. Contact us at: [email protected]

462

chapter 9

1

“We take We made the subtblitele to the the sting...” availa tting it as a header JSP by se ter. new request parame

using JSTL

Doing the same thing with Here we accomplish the same thing we did on the previous page, but using a combination of and . You’ll see that the structure is virtually identical to the one we used with standard actions. 1

The JSP with the <%@ taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core” %> the

OW No slash, because N ... tag has a body


Welcome to our Web Services Support Group.

Contact us at: ${initParam.mainEmail}

2

The included file (“Header.jsp”)


${param.subTitle}


ange at all. It This page doesn’tWchthe parameter got doesn’t care HO it’s there. there, as long as

you are here �

463

URL rewriting in a JSP Sorry to change the subject here... but I just noticed a HUGE problem with JSPs! How can you guarantee session tracking from a JSP... without using scripting?

He missed the point... I said “guarantee”. My real question is--if the client doesn’t support cookies, how can I get URL rewriting to happen? How can I get the session ID added to the URLs in my JSP?

464

chapter 9

Session tracking happens automatically with JSPs, unless you explicitly disable it with a page directive that has a session attribute that says session=”false”.

Ahhh... he obviously doesn’t know about the tag. It does URL rewriting automatically.

using JSTL

for all your hyperlink needs Remember way back in our old servlet days when we wanted to use a session? First we had to get the session (either the existing one or a new one). At that point, the Container knows that it’s supposed to associate the client from this request with a particular session ID. The Container wants to use a cookie—it wants to include a unique cookie with the response, and then the client will send that cookie back with each subsequent request. Except one problem... the client might have a browser with cookies disabled. Then what? The Container will, automatically, fall back to URL rewriting if it doesn’t get a cookie from the client. But with servlets, you STILL have to encode your URLs. In other words, you still have to tell the Container to “append the jsessionid to the end of this particular URL...” for each URL where it matters. Well, you can do the same thing from a JSP, using the tag. URL rewriting from a servlet public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType(“text/html”); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(); out.println(“”); out.println(“click”); out.println(“”); }

o to this URL. Add the extra session ID inf

URL rewriting from a JSP <%@ taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core” %> This is a hyperlink with URL rewriting enabled.

”>Click here



to the end of the This adds the jsessionid co okies are disabled). “value” relative URL (if

you are here �

465

the tag

What if the URL needs encoding? Remember that in an HTTP GET request, the parameters are appended to the URL as a query string. For example, if a form on an HTML page has two text fields—first name and last name—the request URL will stick the parameter names and values on to the end of the request URL. But...an HTTP request won’t work correctly if it contains unsafe characters (although most modern browsers will try to compensate for this). If you’re a web developer, this is old news, but if you’re new to web development, you need to know that URLs often need to be encoded. URL encoding means replacing the unsafe/reserved characters with other characters, and then the whole thing is decoded again on the server side. For example, spaces aren’t allowed in a URL, but you can substitute a plus sign “+” for the space. The problem is, does NOT automatically encode your URLs! Using with a query string Remember, the tag does URL rewriting, but not URL encoding!

“var” Use the optionnalyou want attribute whe value later... access to this

The URL using params is: ${inputURL}


http://localhost:8080/tests/risky.jsp

The URL using params is: /myApp/inputComments. jsp?first=Crouching Pixels&last=Hidden Cursor

rameters have Yikes! Query stringacpaes, for example, to be encoded... sp th a plus “+” sign. must be replaced wi

pposed to have Uh-oh... you’re not su spaces in a URL! Using in the body of

This solves our problem! Now we get both URL rewriting and URL encoding.

no slash





Now the URL looks like this:

use Now we’re safe, beca ding! takes care of the enco

/myApp/inputComments.jsp?firstName=Crouching+Pixels&lastName=Hidden+Cursor

466

chapter 9

using JSTL

I’m interrupting this JSTL talk for a few moments to talk about your error-handling. We’re about to do something that might cause an exception...

You do NOT want your clients to see this:

you are here �

467

error pages

Make your own error pages The guy surfing your site doesn’t want to see your stack trace. And he’s not too thrilled to get a standard “404 Not Found”, either. You can’t prevent all errors, of course, but you can at least give the user a friendlier (and more attractive) error response page. You can design a custom page to handle errors, then use the page directive to configure it. The designated ERROR page (“errorPage.jsp”) <%@ page

isErrorPage=”true” %>

ntainer, “Yes, this IS Confirms for the Co d error page.” an officially-designate

Bummer.

The BAD page that throws an exception (“badPage.jsp”) <%@ page errorPage=”errorPage.jsp” %> About to be bad... <% int x = 10/0; %>

Tells the Contain goes wrong here, er, “If something request to errorPforward the age.jsp”.

What happens when you request “badPage.jsp” http://localhost:8080/tests/badPage.jsp

Bummer.

468

chapter 9

The REQUEST was foatr page “badPage.jsp”, but th, so the threw an exception om RESPONSE came fr “errorPage.jsp”.

using JSTL

It will take me FOREVER to put page directives in all my JSPs, to specify the error page to use. And what if I want a different error page depending on the error? If only there were a way to configure error pages for the whole web app...

She doesn’t know about the DD tag. You can declare error pages in the DD for the entire web app, and you can even configure different error pages for different exception types, or HTTP error code types (404, 500, etc.). The Container uses configuration in the DD as the default, but if a JSP has an explicit errorPage page directive, the Container uses the directive.

you are here �

469

error pages in the DD

Configuring error pages in the DD You can declare error pages in the DD based on either the or the HTTP status number. That way you can show the client different error pages specific to the type of the problem that generated the error.

Declaring a catch-all error page This applies to everything in your web app—not just JSPs. You can override it in individual JSPs by adding a page directive with an errorPage attribute. java.lang.Throwable /errorPage.jsp

Declaring an error page for a more explicit exception This configures an error page that’s called only when there’s an ArithmeticException. If you have both this declaration and the catch-all above, any exception other than ArithmeticException will still end up at the “errorPage.jsp”. java.lang.ArithmeticException /arithmeticError.jsp

Declaring an error page based on an HTTP status code This configures an error page that’s called only when the status code for the response is “404” (file not found). 404 /notFoundError.jsp

470

chapter 9

ich b-app root/context, whhe we e th to ive at rel be ST The MU with a slash. (This is true regardless of whet r means it MUST start on or .) the error page is based

using JSTL

Error pages get an extra object: exception An error page is essentially the JSP that handles the exception, so the Container gives the page an extra object for the exception. You probably won’t want to show the exception to the user, but you’ve got it. In a scriptlet, you can use the implicit object exception, and from a JSP, you can use the EL implicit object ${pageContext.exception}. The object is type java.lang.Throwable, so in a script you can call methods, and with EL you can access the stackTrace and message properties. Note: A more explicit ERROR page (“errorPage.jsp”) <%@ page

isErrorPage=”true” %>

Bummer.


the exception implicit object is available ONLY to error pages with an explicitly-defined page directive:

<%@ page isErrorPage=”true” %> e in In other words, configuring an error pagtainer Con the e mak the DD is not enough to object! give that page the implicit exception

You caused a ${pageContext.exception} on the server.


What happens when you request “badPage.jsp” http://localhost:8080/tests/badPage.jsp

Bummer. You caused a java.lang.ArithmeticException: / by zero on the server.

ore This time, you getabmly details. You prob the won’t show this tothis so user...we just did you could see it.

you are here �

471

the tag What if I think there’s an exception I might be able to recover from in a JSP? What if there are some errors I want to catch myself?

The tag. Like try/catch...sort of If you have a page that invokes a risky tag, but you think you can recover, there’s a solution. You can do a kind of try/catch using the tag, to wrap the risky tag or expression. Because if you don’t, and an exception is thrown, your default error handling will kick in and the user will get the error page declared in the DD. The part that might feel a little strange is that the serves as both the try and the catch—there’s no separate try tag. You wrap the risky EL or tag calls or whatever in the body of a , and the exception is caught right there. But you can’t assume it’s exactly like a catch block, either, because once the exception occurs, control jumps to the end of the tag body (more on that in a minute). <%@ taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core” %> <%@ page errorPage=”errorPage.jsp” %> About to do a risky thing:


<% int x = 10/0; %>

This scriptlet will DEFINITELY cause an exception... but we caught it instead of triggering the error page.

If you see this, we survived.

http://localhost:8080/tests/risky.jsp

About to do a risky thing: If you see this, we survived.

the catch mus have worked... t

472

chapter 9

If this prints out, then we KNOW we made it past the exception (which in this example, means we successfully caught the exception).

using JSTL

But how do I get access to the Exception object? The one that was actually thrown? Since this isn’t an actual error page, the implicit exception object doesn’t work here.

You can make the exception an attribute In a real Java try/catch, the catch argument is the exception object. But with web app error handling, remember, only officially-designated error pages get the exception object. To any other page, the exception just isn’t there. So this does not work: Inside the catch... <% int x = 10/0; %> Exception was: ${pageContext.exception}

this Won’t work becausereror isn’t an official t get page, so it doesn’ject. the exception ob

Using the “var” attribute in Use the optional var attribute if you want to access the exception after the end of the tag. It puts the exception object into the page scope, under the name you declare as the value of var. <%@ taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core” %> <%@ page errorPage=”errorPage.jsp” %> About to do a risky thing:


Inside the catch... <% int x = 10/0; %>

page-scoped This creates a new“myException”, and attribute named ion object to it. assigns the except

There was an exception: ${myException.message}
We survived.

Now there’s an attribu te myException, and since it’s a Throw ab “message” property (bec le, it has a has a getMessage() me ause Throwable thod). you are here �

473

the tag

it does a the way Flow control works in :catch> tag, onc ion object is assigned to it. “var” attribute, the except 1) If you used the optional 2) Flow jumps to below the

. body of the tag



l ntro

co

.. Inside the catch. %> ; /0 10 <% int x = .. h. tc ca e After th

e You’ll NEVER se

this!

We survived. ion object, you must want to use the “var” except Be careful about this. If you y. In other words, there bod end of the the to get you R TE AF il wait unt eption WITHIN the information about the exc any use to y wa no ply sim is tag body. t like a normal Java code tag as being jus It’s tempting to think of a try block, because it’s a acts more like A ’t. isn it but ck, blo ch cat t never needs (or has) a e. Except it’s like a try tha where you put the risky cod this tag for exactly what it sed? The point is—learn catch or finally block. Confu of how a normal try/catch dge your existing knowle into it ng ppi ma n tha er is, rath tag that is below if you see code within the works. And on the exam, fooled. eption is thrown, don’t be the point at which the exc

474

chapter 9

using JSTL

What if you need a tag that’s NOT in JSTL? The JSTL is huge. Version 1.1 has five libraries—four with custom tags, and one with a bunch of functions for String manipulation. The tags we cover in this book (which happen to be the ones you’re expected to know for the exam) are for the generic things you’re most likely to need, but it’s possible that between all five libraries, you’ll find everything you might ever need. On the next page, we’ll start looking at what happens when the tags below aren’t enough. The “Core” library

The “Formatting” library

The “XML” library

General-purpose

Internationalization

Core XML actions























Conditional



XML flow control







Formatting

URL related





Transform actions





The “SQL” library Database access

Iteration











We didn’t cover this one... it lets you iterate over tokens where YOU give it the delimiter. Works a lot like StringTokenizer. We also didn’t cover and , but that gives you a wonderful excuse to get the JSTL docs.





e” library is Only the “cor e exam. covered on th

ry (which by The “core” libra ith “c”) is always prefix w convention we exam. e th on rary covered lib TL JS ly on the e don’t go ecialized, so w The rest are sp least know that you should at into them. But nsformation e. The XML tra they’re availabl your life if you ve ple, could sa am ex r fo , gs ta riting your s RSS feeds. W have to proces in, so make gs can be a pa own custom ta you’re not at u write one th yo re fo be re su wheel. reinventing the

you are here �

475

reading the TLD

Using a tag library that’s NOT from the JSTL Creating the code that goes behind a tag (in other words, the Java code that’s invoked when you put the tag in your JSP) isn’t trivial. We have a whole chapter (the next one) devoted to developing your own custom tag handlers. But the last part of this chapter is about how to use custom tags. What happens, for example, if someone hands you a custom tag library they created for your company or project? How do you know what the tags are and how to use them? With JSTL, it’s easy—the JSTL 1.1 specification documents each tag, including how to use each of the required and optional attributes. But not every custom tag will come so nicely packaged and well-documented. You have to know how to figure out a tag even if the documentation is weak or nonexistent, and, one more thing—you have to know how to deploy a custom tag library.

Main things you have to know: 1

ry, a r ib l m o t s u c a e s To u e TLD. h t d a e r T S U M u yo eed to Everything you n know is in there.

The tag name and syntax The tag has a name, obviously. In , the tag name is set, and the prefix is c. You can use any prefix you want, but the name comes from the TLD. The syntax includes things like required and optional attributes, whether the tag can have a body (and if so, what you can put there), the type of each attribute, and whether the attribute can be an expression (vs. a literal String).

2

The library URI The URI is a unique identifier in the Tag Library Descriptor (TLD). In other words, it’s a unique name for the tag library the TLD describes. The URI is what you put in your taglib directive. It’s what tells the Container how to identify the TLD file within the web app, which the Container needs in order to map the tag name used in the JSP to the Java code that runs when you use the tag.

476

chapter 9

using JSTL

Making sense of the TLD The TLD describes two main things: custom tags, and EL functions. We used one when we made the dice rolling function in the previous chapter, but we had only a element in the TLD. Now we have to look at the element, which can be more complex. Besides the function we declared earlier, the TLD below describes one tag, advice.

hema that c s L M X the ... version of. Don’t memorize it. e h t is is h t T JSP 2.0 > elemen you use forit into your
the developer 1.2

e)— g, not the valuth ta ry. he (t Y R O T A n of e tag libra MAND io rs ve e th re la puts it in to dec

RandomTags MANDATORY; mainly rollIt foo.DiceRoller int rollDice()

randomThings



The unique name we in the taglib direct use ive!

for tools to use..

The EL function we used in the last chap te

r.

ut a really Optional, b

good idea...

random advice

side This is what you use in ! D RE UI Q RE advice is how thaell when e>). vic is ad h y: foo.AdvisorTagHandler Containe uses the tag in a someone empty REQUIRED! This says that the tag must NOT have anything in the body. If your tag has attributes, then one element per tag attribute is required. ribute> user This says you MUST put a “use r” attribute in the tag. true be a r” attribute can (i.e. se “u he t true ys sa s Thi ession al). un ime be a String liter to ve ha ’t sn oe d

r t expr

value

you are here �

477

reading the TLD

Using the custom “advice” tag The “advice” tag is a simple tag that takes one attribute—the user name—and prints out a piece of random advice. It’s simple enough that it could have been just a plain old EL function (with a static method getAdvice(String name)), but we made it a simple tag to show you how it all works...

The TLD elements for the advice tag ... randomThings random advice advice foo.AdvisorTagHandler empty empty

you saw This is the same tageg , but on the previous pa tions. without the annota

user true true


i> es the
JSP that uses the tag

<%@ taglib prefix=”mine” uri=”randomThings”%> Advisor Page




made it The TLD says the tag can’t have a body, so wea slash ). an empty tag (which means the tag ends with

Each library yo needs its own tauglusibe in a page with a unique pref directive ix. 478

chapter 9

> It’s OK to use EL here, because the
using JSTL

The custom tag handler This simple tag handler extends SimpleTagSupport (a class you’ll see in the next chapter), and implements two key methods: doTag(), the method that does the actual work, and setUser(), the method that accepts the attribute value.

Java class that does the tag work package foo; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.SimpleTagSupport; import java.io.IOException;

implements SimpleTagSupport cu stom tags. in things we need

public class AdvisorTagHandler extends SimpleTagSupport { private String user;

when the JSP invokes ) g( Ta do lls ca r ne ai . The Cont declared in the TLD the tag using the name

public void doTag() throws JspException, IOException { getJspContext().getOut().write( “Hello “ + user + “
” ); getJspContext().getOut().write( “Your advice is: “ + getAdvice() ); } public void setUser(String user) { this.user=user; }

}

The Container the tag attributcae.lls this method to set the value fr conventions to figu It uses JavaBean property namin om should be sent to re out that a “user” attribute g the setUser() met hod.

String getAdvice() { String[] adviceStrings = {“That color’s not working for you.”, “You should call in sick.”, “You might want to rethink that haircut.”}; int random = (int) (Math.random() * adviceStrings.length); return adviceStrings[random]; d. rnal metho } r own inte

Ou

don’t use Custom tag handlers s! me na d custom metho tic method, ated a Java class with a sta With EL functions, you cre TLD the d ver you wanted, then use named the method whate ction fun the to > ure . But with custom a custom tag. lare the method name for dec er nev you so (), doTag the TLD! in tion d signature declara Only functions use a metho

you are here �

479

understanding

Pay attention to The is especially important because it tells you whether the value of the attribute is evaluated at translation or runtime. If the is false, or the isn’t defined, you can use only a String literal as that attribute’s value! If you see this: rate true false

OR this: rate true

rvalue>, If there’s no
Then you know THIS WON’T WORK!

<%@ taglib prefix=”my” uri=”myTags”%>



be an NO ! This must NOTt be a expression... it mus String literal.

Q:

You still didn’t answer the question about how you know what type the attribute is...

A:

We’ll start with the easy one. If the is false (or not there at all), then the attribute type can be ONLY a String literal. But if you can use an expression, then you have to hope that it’s either dead obvious from the tag description and attribute name, OR that the developer included the optional subelement of the element. The takes a fully-qualified class name for the type. Whether the TLD declares the type or not, the Container expects the type of the expression to match the type of argument in the tag handler’s setter method for that attribute. In other words, if the tag handler has a setDog(Dog) method for the “dog” attribute, then the value of your expression for that attribute better evaluate to a Dog object! (Or something that can be implicitly assigned to a Dog reference type.)

480

chapter 9

using JSTL

is NOT just for EL expressions You can use three kinds of expressions for the value of an attribute (or tag body) that allows runtime expressions. 1

EL expressions

2

Scripting expressions ’ />

It has to be an expression, not just a scriplet. So it must have the “=” sign in there and no semicolon on the end. 3

standard actions ${userName}

What is this?? I thought this tag didn’t have a body...

BODY of u put attributes in the lets yo clared de ly cit pli ex is tag body a tag, even when the “empty” in the TLD!! nt ibutes to a tag. The key poi alternate way to define attr an ply So . sim is tag > ing ute los ttrib enc p:a the The for EACH the is, there must be only ON the tag (as opposed to in IN tes ibu attr e thre es tak lly ma h atnor t eac tha for tag ute> tags, one if you have a ’ll now have three has an attr ue. val a ting set tribute. Also notice that the you’re er tag’s attribute for which specify the name of the out e... pag t nex the on this There’s a little more about

you are here �

481

tag bodies

What can be in a tag body A tag can have a body only if the element for this tag is not configured with a value of empty. The element can be one of either three or four values, depending on the type of tag.

y. NOT have a bod t us m g a t e h T ts (scriptleths,ave en em el g in t p ri but it CAN NOT have sc The tag mustpressions, and declarations), standard actions. and scriptless scripting ex L and custom E nd a t ex t e templat empty

tagdependent JSP

The tag body is treated as plain text, so the EL is NOT evaluated and tags/actions are not triggered.

The tag body can have anything that can go inside a JSP.

THREE ways to invoke a tag that can’t have a body Each of these are acceptable ways to invoke a tag configured in the TLD with empty. 1

An empty tag
2

/>

slash u put atag, you o y n e h W . pening in the ose a closing tag u don’t

A tag with nothing between the opening and closing tags

We have an ope ning and clo tag, but NOT HING in betwsieeng n.

3

A tag with only tags between the opening and closing tags ${userName}

The tag is the ONLY thin the opening and closing tags of a tag with g you can put between empty! It’s just an alternate way to put thea of tags don’t count as “body attributes in, but content”.

482

chapter 9

using JSTL

The tag handler, the TLD, and the JSP These three handler class,pieces—the tag the JSP are the TLD, and deploy and ruall you need to that uses the n a web app tag.

The tag handler developer creates the TLD to tell both the Container and the JSP developer how to use the tag. A JSP developer doesn’t care about the element in the TLD; that’s for the Container to worry about. The JSP developer cares most about the uri, the tag name, and the tag syntax. Can the tag have a body? Does this attribute have to be a String literal, or can it be an expression? Is this attribute optional? What type does the expression need to evaluate to? Think of the TLD as the API for custom tags. You have to know how to call it and what arguments it needs.

AdvisorTagHandl er class void doTag() { // tag logic }

es the tag JSP that us hings”%> i=”randomT r u ” e n i m ” prefix= <%@ taglib

y>
void setUser(St ring }

user) {

this.user=user;

ge
Advisor Pa

e}” /> ”${userNam = r e s u e c i
TLD file ...

randomThings random advice advice foo.AdvisorTagHandler empty user true true

you are here �

483

the taglib

The taglib is just a name, not a location The element in the TLD is a unique name for the tag library. That’s it. It does NOT need to represent any actual location (path or URL, for example). It simply has to be a name­—the same name you use in the taglib directive. “But,” you’re asking, “how come with the JSTL it gives the full URL to the library?” The taglib directive for the JSTL is: <%@ taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core” %>

URL to This LOOKS likebuat it’s not. a web resource, that happens It’s just a name as a URL. to be formatted

The web Container doesn’t normally try to request something from the uri in the taglib directive. It doesn’t need to use the uri as a location! If you type that as a URL into your browser, you’ll be redirected to a different URL, one that has information about JSTL. The Container could care less that this particular uri happens to also be a valid URL (the whole “http://...” thing). It’s just the convention Sun uses for the uri, to help ensure that it’s a unique name. Su could have named the JSTL uri “java_foo_tags” and it would have worked in exactly the same way. All that matters is that the in the TLD and the uri in the taglib directive match! As a developer, though, you do want to work out a scheme to give your libraries unique values, because names need to be unique for any given web app. You can’t, for example, have two TLD files in the same web app, with the same . So, the domain name convention is a good one, but you don’t necessarily need to use that for all of your in-house development. Having said all that, there is one way in which the uri could be used as a location, but it’s considered a really bad practice—if you don’t specify a inside the TLD, the Container will attempt to use the uri attribute in the taglib directive as a path to the actual TLD. But to hard-code the location of your TLD is obviously a bad idea, so just pretend you don’t know it’s possible.

r a match o f s k o o l r e in a t n The Co D and L T e h t in i> r u < between the directive. ib l g a t e h t in e u l the uri va to be the e v a h T O N s e o d The uri ler! d n a h g a t l a u t c a e location of th 484

chapter 9

using JSTL

The Container builds a map Before JSP 2.0, the developer had to specify a mapping between the in the TLD and the actual location of the TLD file. So when a JSP page had a taglib directive like this: <%@ taglib prefix=”mine” uri=”randomThings”%> The Deployment Descriptor (web.xml) had to tell the Container where the TLD file with a matching was located. You did that with a element in the DD.

The OLD (before JSP 2.0) way to map a taglib uri to a TLD file ... randomThings /WEB-INF/myFunctions.tld

ap the In the DD, mto an actual in the TLD LD file. path to a T

The NEW (JSP 2.0) way to map a taglib uri to a TLD file

No entry in the DD! The Container automatically builds a map between TLD files and names, so that when a JSP invokes a tag, the Container knows exactly where to find the TLD that describes the tag. How? By looking through a specific set of locations where TLDs are allowed to live. When you deploy a web app, as long as you put the TLD in a place the Container will search, the Container will find the TLD and build a map for that tag library. If you do specify an explicit in the DD (web.xml), a JSP 2.0 Container will use it! In fact, when the Container begins to build the -to-TLD map, the Container will look first in your DD to see if you’ve made any entries, and if you have, it’ll use those to help construct the map. For the exam, you’re expected to know about , even though it’s no longer required for JSP 2.0. So the next step is for us to see where the Container looks for TLDs, and also where it looks for the tag handler classes declared in the TLDs.

you are here �

485

TLD locations

Four places the Container looks for TLDs The Container searches in several places to find TLD files—you don’t need to do anything except make sure your TLDs are in one of the right locations.

webapps

1

Directly inside WEB-INF

2

Directly inside a subdirectory of WEB-INF

3

Inside the META-INF directory inside a JAR file that’s inside WEB-INF/lib

4

Inside a sub-directory of META-INF inside a JAR file that’s inside WEB-INF/lib

SampleApp

The JSP that invokes the tag

<%@ taglib prefix=”mine” uri=”/WEB-INF/ myFunctions.tld”%>



WEB-INF

${mine:rollIt()}



useTag.jsp

1



rollIt

tlds

foo.DiceRoller

classes

lib


web.xml

myFunctions.tld

2

rollIt

foo

JAR

foo.DiceRoller



otherTags.tld

META-INF

moreTLDs

3

0010 1100 0001 0101

AdvisorTagHandler.class

rollIt foo.DiceRoller


4

rollIt foo.DiceRoller


catalogTags.tld

486

chapter 9

0001 1001 0011 0110

shoppingTags.tld

A Java class thatom the handles a tag fr library myFunctions.tld

using JSTL

When a JSP uses more than one tag library If you want to use more than one tag library in a JSP, do a separate taglib directive for each TLD. There a few issues to keep in mind...

é

Make sure the taglib uri names are unique. In other words, don’t put in more than one directive with the same uri value.

é

Do NOT use a prefix that’s on the reserved list. The reserved prefixes are: jsp:



jspx:



java:



javax:



servlet:



sun:



sunw:

Sharpen your pencil Empty tags

Write in examples of the THREE different ways to invoke a tag that must have an empty body.

(Check your answers by looking back through the chapter. No, we’re not going to tell you the page number.)

1

2

3 you are here �

487

TLD exercise

Sharpen your pencil How the JSP, the TLD, and the bean attribute class relate Fill in the spaces based on the information that you can see in the TLD. Draw arrows to indicate where the different pieces of information are tied together. In other words, for each blank, show exactly where you found the information needed to fill in the blank. AdvisorTagHandl er class void doTag() { // tag logic }

es the tag JSP that us y>
” uri=” refix=”mine p b i l g a t <%@ ge
Advisor Pa

”%>

void set

(String x) {

// code here }

/> =”${foo}”

:

<

tml>
TLD file ...

randomThings random advice advice foo.AdvisorTagHandler empty user true

488

chapter 9

using JSTL

Sharpen your pencil

1

Test your Tag memory ANSWERS

e The attribute that names th loop counter variable.

Fill in the name of the optional attribute.

2

Fill in the missing attribute name.
4

=”foo”

>

Fill in the missing attribute name.

test =”${userPref==’safety’}” > 3

varStatus

e a value, but you The tag must havval in the body could choose to put the anueattribute. of the tag instead of as

value

=”foo” />

Fill in the missing tag names (two different tag types), and the missing attribute name. test =”${userPref == ‘performance’}”> do drive insanely fast.
otherwise

> Our brakes are the best.


al.

The tag is option

you are here �

489

TLD exercise answers

Sharpen your pencil How the JSP, the TLD, and the bean attribute class relate ANSWERS AdvisorTagHandl er class void doTag() { // tag logic }

es the tag JSP that us y>
ngs”%>

randomThi uri=” ” e n i m ” = x prefi <%@ taglib ge
Advisor Pa

user =”${foo}”
void setUser(Str ing

}

user) {

this.user=user;

/>

TLD file ...

randomThings random advice advice foo.AdvisorTagHandler empty user true

true


490

chapter 9

using JSTL

Mock Exam Chapter 9 1

2

Which is true about TLD files?



 A. TLD files may be placed in any subdirectory of WEB-INF.



B. TLD files are used to configure JSP environment attributes, such as scripting-invalid.



C. TLD files may be placed in the META-INF directory of the WAR file.



D. TLD files can declare both Simple and Classic tags, but TLD files are NOT used to declare Tag Files.

Assuming the standard JSTL prefix conventions are used, which JSTL tags would you use to iterate over a collection of objects? (Choose all that apply.)



 A. 



B. 



C. 



D. 



E. 



F. 

you are here �

491

mock exam

3

4

A JSP page contains a taglib directive whose uri attribute has the value myTags. Which deployment descriptor element defines the associated TLD?



 A.  myTags /WEB-INF/myTags.tld



B.  myTags /WEB-INF/myTags.tld



C.  myTags /WEB-INF/myTags.tld



D.  myTags /WEB-INF/myTags.tld

A JavaBean Person has a property called address. The value of this property is another JavaBean Address with the following string properties: street1, street2, city, stateCode and zipCode. A controller servlet creates a session-scoped attribute called customer that is an instance of the Person bean. Which JSP code structures will set the city property of the customer attribute to the city request parameter? (Choose all that apply.)

492

 

 A. ${sessionScope.customer.address.city = param.city}



C. 



D.  ${param.city}

B. 

chapter 9

using JSTL

5

Which element combinations in the TLD are valid for the following JSP snippet? (Choose all that apply.) 11. 12. 13. <% a = 420; %> 14. 15. value = ${a} 16. 17.

6



 A. tag1 body-content is empty tag2 body-content is JSP tag3 body-content is scriptless



B.  tag1 body-content is JSP tag2 body-content is empty tag3 body-content is scriptless



C. tag1 body-content is JSP tag2 body-content is JSP tag3 body-content is JSP



D. tag1 body-content is scriptless tag2 body-content is JSP tag3 body-content is JSP



E. tag1 body-content is JSP tag2 body-content is scriptless tag3 body-content is scriptless

Assuming the appropriate taglib directives, which are valid examples of custom tag usage? (Choose all that apply.)

    

 A.  B.  C.  D.  E. 

you are here �

493

mock exam

7

Given the following scriptlet code: 11. 12. 13. 14. 15. 16. 17. 18. 19.



Which JSTL code snippet produces the same result?

494



 A. 



B. 



C. 



D. 

chapter 9

using JSTL

Chapter 9 Answers 1

2

(JSP v2.01-160) pgs 3-16,

Which is true about TLD files?



 A. TLD files may be placed in any subdirectory of WEB-INF.



B. TLD files are used to configure JSP environment attributes, such as scripting-invalid.



C. TLD files may be placed in the META-INF directory of the WAR file.



D. TLD files can declare both Simple and Classic tags, but TLD files are NOT used to declare Tag Files. -Option

-Option B is invalid because TLD files configure tag handlers not the JSP environment.

D is invalid because Tag Files may be declared in a TLD (but it is rare).

Assuming the standard JSTL prefix conventions are used, which JSTL tags would you use to iterate over a collection of objects? (Choose all that apply.)



 A. 



B. 



C. 



D. 



E. 



-Option C is invalid because TLD files are not recognized in the META-INF of the WAR file.

F. 

2)

(JSTL v1.1 pg. 4

-Option A is incorrect as this is the tag used for iterating over XPath expressions.

-Option B is incorrect because no such tag exists.

-Option D is incorrect because this tag is used for iterating over tokens within a single string.

-Options E and F are incorrect because the prefix ‘logic’ is not a standard JSTL prefix (this prefix is typically used by tags in the Jakarta Struts package). you are here �

495

mock answers

3

4

-12,13)

(JSP v2.0 pgs 3

A JSP page contains a taglib directive whose uri attribute has the value myTags. Which deployment descriptor element defines the associated TLD?



 A.  myTags /WEB-INF/myTags.tld



B.  myTags /WEB-INF/myTags.tld



C.  myTags /WEB-INF/myTags.tld



D.  - Option D specifies myTags valid tag elements. /WEB-INF/myTags.tld

A JavaBean Person has a property called address. The value of this property is another JavaBean Address with the following string properties: street1, street2, city, stateCode and zipCode. A controller servlet creates a session-scoped attribute called customer that is an instance of the Person bean.

-28)

(JSTL v1.1 pg 4

Which JSP code structures will set the city property of the customer attribute to the city request parameter? (Choose all that apply.)

496

 

 A. ${sessionScope.customer.address.city = param.city}



C. 



D.  ${param.city}

B. 

chapter 9

-Option A is invalid because EL does not permit assignment. -Option C is invalid because the var attribute does not accept a runtime value, nor does it work with the property attribute.

using JSTL

5

Which element combinations in the TLD are valid for the following JSP snippet? (Choose all that apply.) 11. 12. 13. <% a = 420; %> 14. 15. value = ${a} 16. 17.

6

t have at -Tag1 includes scripting cod. eTagso2itismus shown only ent least ‘JSP’ body-cont ‘JSP’ tain con also ld cou it but , as an empty tag s no tain con Tag3 or ‘scriptless’ body-content.e eith or P’ ‘JS er scripting code so it may hav ‘scriptless’ body-content.



 A. tag1 body-content is empty tag2 body-content is JSP tag3 body-content is scriptless



B.  tag1 body-content is JSP tag2 body-content is empty tag3 body-content is scriptless



C. tag1 body-content is JSP tag2 body-content is JSP tag3 body-content is JSP



D. tag1 body-content is scriptless tag2 body-content is JSP tag3 body-content is JSP



E. tag1 body-content is JSP tag2 body-content is scriptless tag3 body-content is scriptless

-Option A is invalid because tag1 cannot be ‘empty’.

-Option D is invalid because tag1 cannot be ‘scriptless’.

Assuming the appropriate taglib directives, which are valid examples of custom tag usage? (Choose all that apply.)

    

dix JSP.C (JSP v2.0 Apgppsen3-21 and 3-30) specifically

n 7)

(JSP v2.0 sectio

 A.  B.  C.  D. 

-Option C is invalid because there is no prefix.

E. 

-Option E is invalid because this is an example of a JSP standard action, not a custom tag. you are here �

497

mock answers

7

48)

(JSTL v1.1 pg 6-

Given the following scriptlet code: 11. 12. 13. 14. 15. 16. 17. 18. 19.



Which JSTL code snippet produces the same result?





498

 A.  -Option B is correct because it uses

proper JSTL tag/attribute names.

B. 



C. 



D. 

chapter 9

the

Subscribe

© Copyright 2013 - 2019 AZDOC.PL All rights reserved.