Praise for Head First Servlets and JSP™
“This Head First Servlets book is as good as the Head First EJB book, which made me laugh AND gave me
97% on the exam!”
—Jef Cumps, J2EE consultant, Cronos
“For our Servlet/JSP classes, we bought more than ten books, without finding any one really satisfying
our teaching needs Until we found the pedagogical gem you now hold in your hands! Head First books
simply make us better teachers Thank you so much for that!”
—Philippe Maquet: Senior Instructor at Loop Factory, Brussels
“There is no better introduction into the Servlet technology on the market than Head First Servlets & JSP.
If you are new to web development with Java and you want an easy read which you really understand,
then you have no other choice but to grab a copy of this book.”
—Oliver Roell, SCJP, SCJD, SCBCD, SCWCD, and SCEA
“Head First Servlets and JSPs is the first book I recommend to developers, both new and experienced,
who are interested in learning to do more with Java EE. Nothing else out there even comes close.
—Theodore Casser, senior software developer, Nanavati Consulting
“I thought I knew JSP/Servlets before picking up Head First, but later after reading the book I really
knew that I know JSP/Servlets. I appreciate the amazing style of writing in the Head First series.”
—Jothi Shankar Kumar. S
“When I read my first book from the Head First series, I realized how much fun learning a technology or
methodology can be. It makes you glide through the learning process so easily, and it makes the learning
stick to the walls of your brains.
The latest one I have read is Head First Servlets & JSP. I picked this one when I was tired of reading big
books for the SCWCD exam After reading this book once, not only did I understand everything, but it
really stayed there. I really really recommend this book to all the aspirants of SCWCD.
—Neeraj Singhal, senior software consultant
Praise for the Head First approach
“Java technology is everywhere—in mobile phones, cars, cameras, printers, games, PDAs, ATMs, smart cards,
gas pumps, sports stadiums, medical devices, Web cams, servers, you name it. If you develop software and
haven’t learned Java, it’s definitely time to dive in—Head First.”
But hidden behind the funny pictures and crazy fonts is a serious, intelligent, extremely well-crafted
presentation of OO Analysis and Design. This book has a strong opinion of how to design programs,
and communicates it effectively. I love the way it uses running examples to lead the reader through the
various stages of the design process. As I read the book, I felt like I was looking over the shoulder of an
expert designer who was explaining to me what issues were important at each step, and why.”
— Edward Sciore, Associate Professor, Computer Science Department
Boston College
“I just finished reading HF OOA&D, and I loved it! The book manages to get across the essentials of
object-oriented analysis and design with UML and use cases, and even several lectures on good software
design, all in a fast-paced, easy to understand way. The thing I liked most about this book was its focus
on why we do OOA&D—to write great software! By defining what great software is and showing how
each step in the OOA&D process leads you towards that goal, it can teach even the most jaded Java
programmer why OOA&D matters. This is a great ‘first book’ on design for anyone who is new to Java,
or even for those who have been Java programmers for a while but have been scared off by the massive
tomes on OO Analysis and Design.”
— Kyle Brown, Distinguished Engineer, IBM
“Head First Software Development is a whimsical but very thoughtfully designed series of information
diagrams and clever illustrations meant to accurately and clearly convey information directly into YOUR
brain. It’s a whole new kind of book.”
— Scott Hanselman
Software Developer, Speaker, Author
Scott Hanselman’s Computer Zen
“Head First Software Development tackles the aspects of software development that are rarely taught in class,
but you REALLY need to know.”
— Keith Wichmann, SOA architect,
Johns Hopkins University, Applied Physics Laboratory
“Head First Software Development teaches many valuable lessons that will help anyone deliver quality
software on time and on budget. Following the core principles taught in this book will help keep your
project on track from start to finish. No matter how long you’ve been developing software, Head First
Software Development will give you essential tools for developing successful projects from start to finish.”
Head First Physics (2008)
Head First Statistics (2008)
Head First Ruby on Rails (2008)
Head First PHP & MySQL (2008)
Beijing • Cambridge • Köln • Paris • Sebastopol • Taipei • Tokyo
Head First
Servlets and JSP™
Second Edition
Wouldn’t it be dreamy
if there were a Servlets book
that was more stimulating than
deleting spam from your inbox?
It’s probably just a fantasy…
Bryan Basham
Kathy Sierra
Bert Bates
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
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
since her days as a game designer
(she wrote games for Virgin, MGM,
and Amblin’) and an AI developer.
She developed much of the Head
First format while teaching New
Media Interactivity for UCLA
Extension’s Entertainment Studies
program. More recently, she’s
been a master trainer for Sun
Microsystems, teaching Sun’s
Java instructors how to teach
the latest Java technologies, and
developing several of Sun’s
certification exams, including
the SCWCD. Together with Bert
Bates, she has been actively using
the Head First concepts to teach
thousands of developers. She
founded one of the largest Java
community websites in the world,
javaranch.com, which won a 2003
and 2004 Software Development
magazine Productivity Award.
She likes running, skiing, horses,
skateboarding, and weird science.
Bert is a longtime software
developer and architect, but a
decade-long stint in artificial
intelligence drove his interest in
learning theory and technology-
Bryan has over twenty years of
software development experience
including time at NASA
developing advanced automation
software using AI techniques. He
also worked for a consulting firm
developing custom OO business
apps. Currently, Bryan is a Course
Developer for Sun, concentrating
on Java and OO design principles.
He’s worked on a large range of
Sun’s Java courses including those
n JDBC, J2EE, Servlets and JSP,
and OO Software Development.
He was also the lead designer of
both the original and new version
of the SCWCD exam.
Bryan is a practicing Zen Buddhist,
Ultimate Frisbee player, audiophile,
and telemark skier.
Kathy
Kathy Sierra
Kathy
has been interested in
Kathy has been interested in Kathy
Kathy
table of contents
ix
Table of Contents (Summary)
Table of Contents (the real thing)
thinking that your life depends on knowing Servlets?
i
table of contents
x
Why use Servlets & JSPs
1
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 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.
Web app architecture
2
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
A Servlet’s REAL job is to handle GET and POST requests. 105
The story of the non-idempotent request 112
What determines whether you get a GET or POST request? 117
Sending and using parameter(s) 119
So that’s the Request now let’s see the Response 126
You can set response headers, you can add response headers 133
Servlet redirect vs. request dispatcher 136
Review: HttpServletResponse 140
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 nd it and how to use it. And your servlet
code has to know how to send a response. Or not
table of contents
xii
Being a web app
5
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
You’ll learn how, why, and what to write in your JSP. And you’ll learn what not to write.
Exam Objectives 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
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
table of contents
xiv
Script-free pages
8
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
learn to use custom tags, and in the next chapter we’ll learn to create our own.
Exam Objectives 440
Looping without scripting <c:forEach> 446
Conditional control with <c:if> and <c:choose> 451
Using the <c:set> and <c:remove> tags 455
With <c:import>, there are now three ways to include content 460
Customizing the thing you include 462
Doing the same thing with <c:param> 463
<c:url> for all your hyperlink needs 465
Make your own error pages 468
The <c:catch> tag. Like try/catch sort of 472
What if you need a tag that’s NOT in JSTL? 475
Pay attention to <rtexprvalue> 480
What can be in a tag body 482
The tag handler, the TLD, and the JSP 483
The taglib <uri> is just a name, not a location 484
When a JSP uses more than one tag library 487
http://localhost:8080/testJSP1/Tester.do
table of contents
xvi
When even JSTL isn’t enough
10
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).
Deploying your web app
11
Keep it secret, keep it safe
12
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?
The power of filters
13
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 con guring a lter 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 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
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
Final mock exam 791
Answers 828
Index
i
865
xix
Make it Stick
Intro
how to use this book
I can’t believe
they put
that
in a
programming book!
In this section, we answer the burning question:
“So, why DID they put that in a programming book?”
xx
intro
1
2
3
Who is this book for?
Who should probably back away from this book?
If you can answer “yes” to all of these:
how to use this book
the intro
you are here�
xxi
Great. Only
800 more dull,
dry, boring pages.
We know what you’re thinking.
And we know what your
brain
is thinking.
How can this be a serious programming book?”
What’s with all the graphics?”
Can I actually learn it this way?”
Your brain craves novelty. It’s always searching, scanning, waiting for
something unusual. It was built that way, and it helps you stay alive.
So what does your brain do with all the routine, ordinary, normal things
you encounter? Everything it can to stop them from interfering with the
brain’s real job—recording things that matter. It doesn’t bother saving
the boring things; they never make it past the “this is obviously not
important” filter.
How does your brain know what’s important? Suppose you’re out for
a day hike and a tiger jumps in front of you, what happens inside your
head and body?
Neurons fire. Emotions crank up. Chemicals surge.
And that’s how your brain knows
This must be important! Don’t forget it!
But imagine you’re at home, or in a library. It’s a safe, warm, tiger-free zone.
You’re studying. Getting ready for an exam. Or trying to learn some
tough technical topic your boss thinks will take a week, ten days at
Make it visual.
Images are far more memorable than words alone, and
make learning much more effective (up to 89% improvement in recall and
transfer studies). It also makes things more understandable.
Put the words
within or near the graphics
they relate to, rather than on the bottom
or on another page, and learners will be up to
twice
as likely to solve problems
related to the content.
Use a conversational and personalized style.
In
recent studies, students performed up to 40% better on post-learning
tests if the content spoke directly to the reader, using a first-person,
conversational style rather than taking a formal tone. Tell stories
instead of lecturing. Use casual language. Don’t take yourself
too seriously. Which would
you
pay more attention to: a
stimulating dinner party companion, or a lecture?
Get the learner to think more deeply.
In other words,
unless you actively flex your neurons, nothing much happens in your head. A reader
has to be motivated, engaged, curious, and inspired to solve problems, draw conclusions,
and generate new knowledge. And for that, you need challenges, exercises, and thought-
provoking questions, and activities that involve both sides of the brain and multiple senses.
Get—and keep—the reader’s attention.
We’ve all had the “I really want to learn
this but I can’t stay awake past page one” experience. Your brain pays attention to things
xxiii
If you really want to learn, and you want to learn more quickly and more deeply,
pay attention to how you pay attention. Think about how you think. Learn how you
learn.
Most of us did not take courses on metacognition or learning theory when we were
growing up. We were expected to learn, but rarely taught to learn.
But we assume that if you’re holding this book, you really want to learn how to build
web applications in Java, and pass the SCWCD exam. And you probably don’t want
to spend a lot of time. If you want to use what you read in this book, you need to
remember what you read. And for that, you’ve got to understand it. To get the most from
this book, or any book or learning experience, take responsibility for your brain. Your
brain on this content.
The trick is to get your brain to see the new material you’re learning
as Really Important. Crucial to your well-being. As important as
a tiger. Otherwise, you’re in for a constant battle, with your brain
doing its best to keep the new content from sticking.
Metacognition: thinking about thinking
I wonder how I
can trick my brain
into remembering
this stuff
So just how
DO
you get your brain to treat
servlets like it’s a hungry tiger?
There’s the slow, tedious way, or the faster, more effective way.
The slow way is about sheer repetition. You obviously know that
you are able to learn and remember even the dullest of topics
if you keep pounding the same thing into your brain. With enough
repetition, your brain says, “This doesn’t feel important to him, but he keeps looking at