Home Page Icon
Home Page
Table of Contents for
Son of more tag attributes
Close
Son of more tag attributes
by Bert Bates, Bryan Basham, Kathy Sierra
Head First Servlets and JSP, 2nd Edition
Head First Servlets and JSP™
Dedication
A Note Regarding Supplemental Files
Praise for Head First Servlets and JSP™
Praise for the Head First approach
Perpetrators of the Head First series (and this book)
How to Use this Book: Intro
Who is this book for?
Who should probably back away from this book?
We know what you’re thinking.
And we know what your brain is thinking
Metacognition: thinking about thinking
Here’s what WE did
Here’s what YOU can do to bend your brain into submission
What you need for this book
Last-minute things you need to know
About the SCWCD (for Java EE 1.5) exam
Beta testers & technical reviewers
Other people to : credit
Even more people
1. Intro and Overview: Why use Servlets & JSPs?
Everybody wants a web site
What does your web server do?
What does a web client do?
Clients and servers know HTML and HTTP
Two-minute HTML guide
What you write... (the HTML)
What the browser creates...
What is the HTTP protocol?
HTML is part of the HTTP response
If that’s the response, what’s in the request?
GET is a simple request, POST can send user data
It’s true... you can send a little data with HTTP GET
Anatomy of an HTTP GET request
Anatomy of an HTTP POST request
Anatomy of an HTTP response, and what the heck is a “MIME type”?
All the pieces. On one page.
URL. Whatever you do, don’t pronounce it “Earl”.
Directory structure for a simple Apache web site
Web servers love serving static web pages
But sometimes you need more than just the web server
Two things the web server alone won’t do
The non-Java term for a web server helper app is “CGI” program
Servlets and CGI both play the role of a helper app in the web server
Servlets Demystified (write, deploy, run)
Actually, trying to format HTML inside a servlet’s out.println() pretty much sucks.
JSP is what happened when somebody introduced Java to HTML
2. High-Level Overview: Web App Architecture
What is a Container?
What if you had Java, but no servlets or Containers?
What does the Container give you?
How the Container handles a request
How it looks in code (what makes a servlet a servlet)
You’re wondering how the Container found the Servlet...
A servlet can have THREE names
Using the Deployment Descriptor to map URLs to servlets
But wait! There’s more you can do with the DD
Story: Bob Builds a Matchmaking Site
He starts to build a bunch of servlets... one for each page
But then it gets ugly, so he adds JSPs
But then his friend says, “You ARE using MVC, right?”
The Model-View-Controller (MVC) Design Pattern fixes this
Applying the MVC pattern to the matchmaking web app
But then his friend Kim takes a look
Is there an answer?
A “working” Deployment Descriptor (DD)
How J2EE fits into all this
3. Hands-on MVC: Mini MVC Tutorial
Let’s build a real (small) web application
The User’s View of the web application—a Beer Advisor
Here’s the architecture...
Creating your development environment
Creating the deployment environment
Our roadmap for building the app
The HTML for the initial form page
Deploying and testing the opening page
Mapping the logical name to a servlet class file
The first version of the controller servlet
Compiling, deploying, and testing the controller servlet
Building and testing the model class
Enhancing the servlet to call the model, so that we can get REAL advice...
Servlet version two code
Key steps for servlet version two
Review the partially completed, MVC beer advice web application
Create the JSP “view” that gives the advice
Enhancing the servlet to “call” the JSP (version three)
Code for servlet version three
Compile, deploy, and test the final app!
There is still so much to learn.
4. Request and Response: Being a Servlet
Servlets are controlled by the Container
But there’s more to a servlet’s life
Your servlet inherits the lifecycle methods
The Three Big Lifecycle Moments
Each request runs in a separate thread!
In the beginning: loading and initializing
Servlet Initialization: when an object becomes a servlet
But a Servlet’s REAL job is to handle requests. That’s when a servlet’s life has meaning.
Request and Response: the key to everything, and the arguments to service()
The HTTP request Method determines whether doGet() or doPost() runs
Actually, one or more of the other HTTP Methods might make a (brief) appearance on the exam...
The difference between GET and POST
No, it’s not just about the size
The story of the non-idempotent request
POST is not idempotent
What determines whether the browser sends a GET or POST request?
What happens if you do NOT say method=“POST” in your <form>?
POST is NOT the default!
Sending and using a single parameter
Sending and using TWO parameters
Besides parameters, what else can I get from a Request object?
Review: servlet lifecycle and API
Review: HTTP and HttpServletRequest
So that’s the Request... now let’s see the Response
Using the response for I/O
Imagine you want to send a JAR to the client...
Servlet code to download the JAR
Whoa. What’s the deal with content type?
You’ve got two choices for output: characters or bytes
You can set response headers, you can add response headers
But sometimes you just don’t want to deal with the response yourself...
Servlet redirect makes the browser do the work
Using relative URLs in sendRedirect()
A request dispatch does the work on the server side
Redirect vs. Request Dispatch
Review: HttpServletResponse
Coffee Cram: Mock Exam Chapter 4
Coffee Cram: Chapter 4 Answers
5. Attributes and Listeners: Being a Web App
Kim wants to configure his email address in the DD, not hard-code it inside the servlet class
Init Parameters to the rescue
You can’t use servlet init parameters until the servlet is initialized
The servlet init parameters are read only ONCE—when the Container initializes the servlet
Testing your ServletConfig
How can a JSP get servlet init parameters?
What about the way we did it with the beer app? We passed the model info to the JSP using a request attribute...
Setting a request attribute works... but only for the JSP to which you forwarded the request
Context init parameters to the rescue
Remember the difference between servlet init parameters and context init parameters
ServletConfig is one per servlet ServletContext is one per web app
So what else can you do with your ServletContext?
What if you want an app init parameter that’s a database DataSource?
What she really wants is a listener.
She wants a ServletContextListener
Tutorial: a simple ServletContextListener
Making and using a context listener
We need three classes and one DD
Writing the listener class
Writing the attribute class (Dog)
Writing the servlet class
Writing the Deployment Descriptor
Compile and deploy
Try it out
Troubleshooting
The full story...
Listeners: not just for context events...
The eight listeners
The HttpSessionBindingListener
What, exactly, is an attribute?
Attributes are not parameters!
The Three Scopes: Context, Request, and Session
Attribute API
The dark side of attributes...
But then something goes horribly wrong...
Context scope isn’t thread-safe!
The problem in slow motion...
How do we make context attributes thread-safe?
Synchronizing the service method is a spectacularly BAD idea
Synchronizing the service method won’t protect a context attribute!
You don’t need a lock on the servlet... you need the lock on the context!
Are Session attributes thread-safe?
What’s REALLY true about attributes and thread-safety?
Protect session attributes by synchronizing on the HttpSession
SingleThreadModel is designed to protect instance variables
But how does the web container guarantee a servlet gets only one request at a time?
Which is the better STM implementation?
Only Request attributes and local variables are thread-safe!
Request attributes and Request dispatching
RequestDispatcher revealed
What’s wrong with this code?
You’ll get a big, fat IllegalStateException!
Coffee Cram: Mock Exam Chapter 5
Coffee Cram: Chapter 5 Answers
6. Session Management: Conversational state
Kim wants to keep client-specific state across multiple requests
It’s supposed to work like a REAL conversation...
How can he track the client’s answers?
How sessions work
One problem... how does the Container know who the client is?
The client needs a unique session ID
How do the Client and Container exchange Session ID info?
Cookies
The best part: the Container does virtually all the cookie work!
What if I want to know whether the session already existed or was just created?
What if I want ONLY a pre-existing session?
You can do sessions even if the client doesn’t accept cookies, but you have to do a little more work...
URL rewriting: something to fall back on
URL rewriting kicks in ONLY if cookies fail, and ONLY if you tell the response to encode the URL
URL rewriting works with sendRedirect()
Getting rid of sessions
How we want it to work...
The HttpSession interface
Key HttpSession methods
Setting session timeout
Can I use cookies for other things, or are they only for sessions?
Using Cookies with the Servlet API
Simple custom cookie example
Custom cookie example continued...
Key milestones for an HttpSession
Session lifecycle Events
Don’t forget about HttpSessionBindingListener
Session migration
The Beer Web App distributed across two VMs
Session migration in action
HttpSessionActivationListener lets attributes prepare for the big move...
Listener examples
Listener examples
Listener examples
Session-related Listeners
Session-related Event Listeners and Event Objects API overview
Session-related Listeners
Coffee Cram: Mock Exam Chapter 6
Coffee Cram: Chapter 6 Answers
7. Using JSP: Being a JSP
In the end, a JSP is just a servlet
Making a JSP that displays how many times it’s been accessed
She deploys and tests it
The JSP doesn’t recognize the Counter class
Use the page directive to import packages
But then Kim mentions “expressions”
Expressions become the argument to an out.print()
Kim drops the final bombshell...
Declaring a variable in a scriptlet
What REALLY happens to your JSP code?
We need another JSP element...
JSP Declarations
Time to see the REAL generated servlet
The out variable isn’t the only implicit object...
A comment...
API for the generated servlet
Lifecycle of a JSP
Translation and compilation happens only ONCE
Initializing your JSP
Configuring servlet init parameters
Overriding jspInit()
Attributes in a JSP
Using PageContext for attributes
Examples using pageContext to get and set attributes
While we’re on the subject... let’s talk more about the three directives
Attributes to the page directive
Scriptlets considered harmful?
There didn’t used to BE an alternative.
EL: the answer to, well, everything.
Sneak peek at EL
Using <scripting-invalid>
You can choose to ignore EL
El is enabled by default!
But wait... there’s still another JSP element we haven’t seen: actions
Coffee Cram: Mock Exam Chapter 7
Coffee Cram: Chapter 7 Answers
8. Scriptless JSP: Script-free pages
Our MVC app depends on attributes
But what if the attribute is not a String, but an instance of Person?
We need more code to get the Person’s name
Person is a JavaBean, so we’ll use the bean-related standard actions
Deconstructing <jsp:useBean> and <jsp:getProperty>
Declare and initialize a bean attribute with <jsp:useBean>
Get a bean attribute’s property value with <jsp:getProperty>
<jsp:useBean> can also CREATE a bean!
You can use <jsp:setProperty>
<jsp:useBean> can have a body!
Generated servlet when <jsp:useBean> has a body
Can you make polymorphic bean references?
Adding a type attribute to <jsp:useBean>
Using type without class
The scope attribute defaults to “page”
Going straight from the request to the JSP without going through a servlet...
The param attribute to the rescue
But wait ! It gets even better...
If you can stand it, it gets even BETTER...
Bean tags convert primitive properties automatically
But what if the property is something OTHER than a String or primitive?
Trying to display the property of the property
Expression Language (EL) saves the day!
Deconstructing the JSP Expression Language (EL)
Using the dot (.) operator to access properties and map values
The [] operator is like the dot only way better
The [] gives you more options...
Using the [] operator with an array
A String index is coerced to an int for arrays and Lists
For beans and Maps you can use either operator
If it’s NOT a String literal, it’s evaluated
You can use nested expressions inside the brackets
You can’t do ${foo.1}
EL renders raw text, including HTML
The same is true for JSP expression tags...
... and for the jsp:getProperty standard action
The EL implicit objects
Request parameters in EL
What if you want more information from the request?
The requestScope is NOT the request object
Scope implicit objects can save you
Getting Cookies and init params
She doesn’t know about EL functions
Imagine you want your JSP to roll dice
Deploying an app with static functions
And a few other EL operators...
EL handles null values gracefully
JSP Expression Language (EL) review
Reusable template pieces
The include directive
The <jsp:include> standard action
They’re NOT the same underneath...
The include directive happens at translation time <jsp:include> happens at runtime
The include directive at first request
The <jsp:include> standard action at first request
Uh-oh. She’s right...
The way we SHOULD have done it
Customizing the included content with <jsp:param>
The <jsp:forward> standard action
A conditional forward...
How it runs...
With <jsp:forward>, the buffer is cleared BEFORE the forward
She doesn’t know about JSTL tags
Bean-related standard action review
The include review
Coffee Cram: Mock Exam Chapter 8
Coffee Cram: Chapter 8 Answers
9. Using JSTL: Custom tags are powerful
EL and standard actions are limited
The case of the disappearing HTML (reprised)
There’s a better way: use the <c:out> tag
You can explicitly declare the conversion of XML entities
You can explicitly declare NO conversion of XML entities
Conversion happens by default
Null values are rendered as blank text
Set a default value with the default attribute
Or you can do it this way:
Looping without scripting
<c:forEach>
Deconstructing <c:forEach>
You can even nest <c:forEach> tags
Doing a conditional include with <c:if>
But what if you need an else?
The <c:if> tag won’t work for this
The <c:choose> tag and its partners <c:when> and <c:otherwise>
The <c:set> tag... so much cooler than <jsp:setProperty>
Using <c:set> with beans and Maps
Key points and gotchas with <c:set>
<c:remove> just makes sense
With <c:import>, there are now THREE ways to include content
<c:import> can reach OUTSIDE the web app
Customizing the thing you include
Doing the same thing with <c:param>
<c:url> for all your hyperlink needs
What if the URL needs encoding?
You do NOT want your clients to see this:
Make your own error pages
She doesn’t know about the <error-page> DD tag.
Configuring error pages in the DD
Error pages get an extra object: exception
The <c:catch> tag. Like try/catch...sort of
You can make the exception an attribute
What if you need a tag that’s NOT in JSTL?
Using a tag library that’s NOT from the JSTL
Making sense of the TLD
Using the custom “advice” tag
The custom tag handler
Pay attention to <rtexprvalue>
<rtexprvalue> is NOT just for EL expressions
What can be in a tag body
The tag handler, the TLD, and the JSP
The taglib <uri> is just a name, not a location
The Container builds a map
Four places the Container looks for TLDs
When a JSP uses more than one tag library
Coffee Cram: Mock Exam Chapter 9
Coffee Cram: Chapter 9 Answers
10. Custom Tag Development: When even JSTL is not enough...
Includes and imports can be messy
Tag Files: like include, only better
But how do you send it parameters?
To a Tag File, you don’t send request parameters, you send tag attributes!
Aren’t tag attributes declared in the TLD?
Tag Files use the attribute directive
When an attribute value is really big
Declaring body-content for a Tag File
Where the Container looks for Tag Files
When you need more than Tag Files... Sometimes you need Java
Making a Simple tag handler
A Simple tag with a body
The Simple tag API
The life of a Simple tag handler
What if the tag body uses an expression?
A tag with dynamic row data: iterating the body
A Simple tag with an attribute
What exactly IS a JspFragment?
SkipPageException: stops processing the page...
SkipPageException shows everything up to the point of the exception
But what happens when the tag is invoked from an included page?
SkipPageException stops only the page that directly invoked the tag
You still have to know about Classic tag handlers
Tag handler API
A very small Classic tag handler
A Classic tag handler with TWO methods
When a tag has a body: comparing Simple vs. Classic
Classic tags have a different lifecycle
The Classic lifecycle depends on return values
IterationTag lets you repeat the body
Default return values from TagSupport
OK, let’s get real...
Our dynamic <select> tag isn’t complete...
We could just add more custom tag attributes...
Son of more tag attributes
The return of the son of more tag attributes
I’m getting sick of these tag attributes!
Our tag handler code using the DynamicAttributes interface
The rest of the tag handler code
OK, there is a little bit of configuration in the TLD
What about Tag Files?
But what if you DO need access to the body contents?
With BodyTag, you get two new methods
With BodyTag, you can buffer the body
What if you have tags that work together?
A Tag can call its Parent Tag
Find out just how deep the nesting goes...
Simple tags can have Classic parents
You can walk up, but you can’t walk down...
Getting info from child to parent
Menu and MenuItem tag handlers
Getting an arbitrary ancestor
Using the PageContext API for tag handlers
Coffee Cram: Mock Exam Chapter 10
Coffee Cram: Chapter 10 Answers
11. Web App Deployment: Deploying your web app
The Joy of Deployment
What goes where in a web app
What she really wants is a WAR file
WAR files
What a deployed WAR file looks like
Making static content and JSPs directly accessible
How servlet mapping REALLY works
Servlet mappings can be “fake”
Subtle issues...
Configuring welcome files in the DD
How the Container chooses a welcome file
Configuring error pages in the DD
Configuring servlet initialization in the DD
Making an XML-compliant JSP: a JSP Document
Memorizing the EJB-related DD tags
Memorizing the JNDI <env-entry> DD tag
Memorizing the <mime-mapping> DD tag
Coffee Crem: Mock Exam Chapter 11
Coffee Crem: Chapter 11 Answers
12. Web App Security: Keep it secret, keep it safe
The Bad Guys are everywhere
And it’s not just the SERVER that gets hurt...
The Big 4 in servlet security
A little security story
How to Authenticate in HTTP World: the beginning of a secure transaction
A slightly closer look at how the Container does Authentication and Authorization
How did the Container do that ?
Keep security out of the code!
Who implements security in a web app?
The Big Jobs in servlet security
Just enough Authentication to discuss Authorization
Authorization Step 1: defining roles
Authorization Step 2: defining resource/method constraints
The <security-constraint> rules for <web-resource-collection> elements
Picky <security-constraint> rules for <auth-constraint> sub-elements
The way <auth-constraint> works
How multiple <security-constraint> elements interact
Dueling <auth-constraint> elements
Alice’s recipe servlet, a story about programmatic security...
Customizing methods: isUserInRole()
The declarative side of programmatic security
Authentication revisited
Implementing Authentication
Form-Based Authentication
Summary of Authentication types
She doesn’t know about J2EE’s “protected transport layer connection”
Securing data in transit: HTTPS to the rescue
How to implement data confidentiality and integrity sparingly and declaratively
Protecting the request data
Coffee Cram: Mock Exam Chapter 12
Coffee Cram: Chapter 12 Answers
13. Filters and Wrappers: The Power of Filters
Enhancing the entire web application
How about some kind of “filter”?
Filters are modular, and configurable in the DD
Three ways filters are like servlets
Building the request tracking filter
A filter’s life cycle
Think of filters as being “stackable”
A conceptual call stack example
Declaring and ordering filters
News Flash: As of version 2.4, filters can be applied to request dispatchers
Compressing output with a response-side filter
Architecture of a response filter
But is it really that simple?
The output has left the building
We can implement our OWN response
She doesn’t know about the servlet Wrapper classes
Wrappers rock
Adding a simple Wrapper to the design
Add an output stream Wrapper
The real compression filter code
“Off the path”
Compression wrapper code
Compression wrapper, helper class code
Coffee Cram: Mock Exam Chapter 13
Coffee Cram: Chapter 13 Answers
14. Patterns and Struts: Enterprise Design Patterns
Web site hardware can get complicated
Web application software can get complicated
Lucky for us, we have J2EE patterns
Common pressures
Performance (and the “ilities”)
Aligning our vernaculars...
Code to interfaces
Separation of Concerns & Cohesion
Hide Complexity
More design principles...
Loose Coupling
Remote Proxy
Increase Declarative Control
Patterns to support remote model components
A Fable: The Beer App Grows
How the Business Team supports the web designers when the MVC components are running on one JVM
How will they handle remote objects?
RMI makes life easy
What we want...
How RMI pulls it off
Just a little more RMI review
Adding RMI and JNDI to the controller
How about a “go-between” object?
The “go-between” is a Business Delegate
Simplify your Business Delegates with the Service Locator
Protecting the web designer’s JSPs from remote model complexity
Compare the local model diagram to this remote model diagram
There’s good news and bad news...
Time for a Transfer Object?
Service Locator and Business Delegate both simplify model components
Business tier patterns: quick review
Our very first pattern revisited... MVC
Where we left off...
MVC in a real web app
Looking at the MVC controller
Improving the MVC controllers
New and (shorter) controller pseudo-code
Designing our fantasy controller
Yes! It’s Struts in a nutshell
Is Struts a container?
How does Front Controller fit in?
Refactoring the Beer app for Struts
The Struts Beer app architecture
A form bean exposed
How an Action object ticks
struts-config.xml: tying it all together
Specifying Struts in the web.xml DD
Install Struts, and Just Run It!
Creating the deployment environment
Patterns review for the SCWCD
Business Delegate
Service Locator
Transfer Object
Intercepting Filter
Model, View, Controller (MVC)
Front Controller
Coffee Cram: Mock Exam Chapter 14
Coffee Cram: Chapter 14 Answers
A. Final Mock Exam: Coffee Cram
Coffee Cram: Final Mock Exam
Coffee Cram: Final Exam Answers
B.
C.
Index
About the Authors
Copyright
Search in book...
Toggle Font Controls
Playlists
Add To
Create new playlist
Name your new playlist
Playlist description (optional)
Cancel
Create playlist
Sign In
Email address
Password
Forgot Password?
Create account
Login
or
Continue with Facebook
Continue with Google
Sign Up
Full Name
Email address
Confirm Email Address
Password
Login
Create account
or
Continue with Facebook
Continue with Google
Prev
Previous Chapter
We could just add more custom tag attributes...
Next
Next Chapter
The return of the son of more tag attributes
Son of more tag attributes
Add Highlight
No Comment
..................Content has been hidden....................
You can't read the all page of ebook, please click
here
login for view all page.
Day Mode
Cloud Mode
Night Mode
Reset