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...55 downloads 671 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]
Kathy Sierra, Bert Bates
Brett D. McLaughlin
Edie Freedman, Steve Fehler, Louise Barr
Kathy Sierra and Bert Bates
Assistant to the Front Controller:
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
Why use Servlets & JSPs: an introduction
Web App Architecture: high-level overview
Mini MVC Tutorial: hands-on MVC
Being a Servlet: request AND response
Being a Web App: attributes and listeners
Conversational state: session management
Being a JSP: using JSP
Script-free pages: scriptless JSP
Custom tags are powerful: using JSTL
When even JSTL is not enough: custom tag development
Deploying your web app: web app deployment
Keep it secret, keep it safe: web app security
The Power of Filters: wrappers and filters
Enterprise design patterns: patterns and struts
Appendix A: Final Mock Exam
Table of Contents (the real thing)
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?
We know what your brain is thinking
Bend your brain into submission
What you need for this book
Passing the certification exam
table of contents
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.
What web servers and clients do, and how they talk?
Two-minute guide to HTML
What is the HTTP protocol?
Anatomy of HTTP GET and POST requests and HTTP responses
Locating web pages using URLs
Web servers, static web pages, and CGI
Servlets Demystified: write, deploy, and run a servlet
JSP is what happened when somebody introduced Java to HTML
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 ﬁrst look at the MVC pattern.
What is a Container and what does it give you?
How it looks in code (and what makes a servlet)
Naming servlets and mapping them to URLs using the DD
Story: Bob Builds a Matchmaking Site ( and MVC intro)
A Model-View-Controller (MVC) overview and example
A “working” Deployment Descriptor (DD)
How J2EE fits into all this
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 ﬁrst, 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
Let’s build an MVC application; the first design
Create the development and deployment environments
Create and test the HTML for the initial form page
Create the Deployment Descriptor (DD)
Create, compile, deploy, and test the controller servlet
Design, build, and test the model component
Enhance the controller to call the model
Create and deploy the view component (it’s a JSP)
Enhance the controller servlet to call the JSP
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 ﬁnd 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
table of contents
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.
Init Parameters and ServletConfig to the rescue
How can a JSP get servlet init parameters?
Context init parameters to the rescue
Comparing ServletConfig with ServletContext
She wants a ServletContextListener
Tutorial: a simple ServletContextListener
Compile, deploy, and test your listener
The full story, a ServletContextListener review
Eight Listeners: they’re not just for context events...
What, exactly, is an attribute?
The Attribute API and the dark side of attributes
Context scope isn’t thread-safe!
The problem in slow motion...
Trying out Synchronization
Are Session attributes thread-safe?
Only Request attributes and local variables are thread-safe!
Request attributes and Request dispatching
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
It’s supposed to be a conversation, (how sessions work)
Session IDs, cookies, and other session basics
URL rewriting: something to fall back on
When sessions get stale; getting rid of bad sessions
Key milestones for an HttpSession
Don’t forget about HttpSessionBindingListener
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-ﬂedged 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
Create a simple JSP using “out” and a page directive
JSP expressions, variables, and declarations
Time to see a JSP-generated servlet
The out variable isn’t the only implicit object...
The Lifecycle and initialization of a JSP
While we’re on the subject... let’s talk more about the three directives
Scriptlets considered harmful? Here’s EL
But wait... we haven’t seen: actions
table of contents
When attributes are beans
Standard actions: useBean, getProperty, setProperty
Can you make polymorphic bean references?
The param attribute to the rescue
Expression Language (EL) saves the day!
Using the dot (.) operator to access properties and map values
The  gives you more options (Lists, arrays...)
More dot and [ ] operator details
The EL implicit objects
EL functions, and handling “null”
Reusable template pieces—two kinds of “include”
She doesn’t know about JSTL tags (a preview)
Reviewing standard actions and include
table of contents
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.
Looping without scripting
Conditional control with
Customizing the thing you include
Doing the same thing with