Reading Notes for Chapter 4,
Head First Servlets and JSP

P. Conrad, CISC474, Spring 2006

Table of Contents

93 Being a Servlet 112 The story of the non-idempotent request 131 There are no Dumb Questions.
94 Objectives 113 Our story continues... 132 You've got two choices for output: characters or bytes
95 Servlets are controlled by the Container 114 Sharpen your pencil and Flex Your Mind 133 You can set response headers, you can add response headers
96 The story continues... 115 Being idempotent is GOOD (... no unwanted side effects!) 134 But sometimes you just don't want to deal with the response yourself...
97 But there's more to a servlet's life 116 POST is not idempotent 135 (p. 134 continued)
98 Your servlet inherits the lifecycle methods 117 What determines whether the browser sends a GET or POST request? 136 Servlet redirect makes the browser do the work
99 The Three Big Lifecycle Moments 118 POST is NOT the default! 137a You can't do a sendRedirect after writing to the response!
100 The service() method is always called in its own stack... 119 Sending and using a single parameter 137b sendRedirect() takes a String, NOT a URL object!
101 Each request runs in a separate thread! 120 Sending and using TWO parameters 138 A request dispatch does the work on the server side
102 In the beginning: loading and initializing 121 You can have multiple values for a single parameter! 139 Redirect vs. Request Dispatch
103 Servlet Initialization: when an object becomes a servlet 122 Beside parameters, what else can I get from a Request object? 140 Review: HttpServletResponse
104 What does 'being a servlet' buy you? 123 There are no Dumb Questions (about Request object methods) 141 Coffee Cram (Mock Exam Chapter 4, Q1-Q3)
105 But a Servlet's REAL job is to handle requests. 124 Review: servlet lifecycle and API 142 Coffee Cram (Mock Exam Chapter 4, Q4-Q7)
106 Request and Response: the key to everything, and the arguments to service() 125 Review: HTTP and HttpServletRequest 143 Coffee Cram (Mock Exam Chapter 4, Q8-Q10)
107 There are no dumb questions
(about HttpServletRequest and HttpServlet Response)
126 So that's the Request... now let's see the Response 144 Coffee Cram (Mock Exam Chapter 4, Q1-Q3 answers)
108 The HTTP request Method determines whether doGet() or doPost() runs 127 Using the response for I/O 145 Coffee Cram (Mock Exam Chapter 4, Q4-Q7 answers)
109 Actually, one or more of the other HTTP Methods might make a (brief) appearance on the exam 128 Imagine you want to send a JAR to the client... 146 Coffee Cram (Mock Exam Chapter 4, Q8-Q10 answers)
110 The difference between GET and POST 129 Servlet code to download the JAR    
111 No, its not just about the size 130 Whoa. What's the deal with content type?    

p93 Being a Servlet

The big picture: a servlet takes a request and turns it into a response. But there is a lot of detail, including (as the cartoon alludes to)

p94 Objectives

Check the confirmed errata for this page

Ok, the "intro" part of the book is over. From this point forward, if you were taking the SCWCDE exam you'd need to pay close attention and make sure that by the end of the chapter, you've really learned all the things listed on the objectives page of each chapter.

For the purposes of CISC474, the objectives listed on this page are all pretty important. So I'd encourage you to follow the advice in italics on this page, and take these objectives seriously.

p95 Servlets are controlled by the Container
p96 The story continues...

Take some time understand the diagram on these two pages. You are going to need to "have this picture in your head" as you work with creating web applications using Java—particularly as we get fancier and start using JSPs and stuff.

p97 But there's more to a servlet's life

This is an important page in terms of understanding how to build web apps.

An example of why this page is important

Suppose you want to incorporate database access into a servlet. You might use the example code from Sebesta, Section 14.7.5 which illustrates how to use a MySQL database with a Java Servlet, or my revised version of that code.

In Sebesta's code, you'll see that the logic is divided between the init() method and the doPost() method of the HttpServlet class. (In my version, I use doGet() instead of doPost().) This page shows how these methods fit into the big picture of the life of a servlet.

p98 Your servlet inherits the lifecycle methods

As the "handwritten NOTE" at the upper right hand corner of the page says, this page isn't for memorizing details—rather, its here to help you see how the HttpServlet class fits into a larger inheritance hierarchy. You may need to have these inheritance relationships in mind when you are looking through the Java API documentation for the methods you need.

At the bottom of this hierarchy is the actual servlet you are going to create yourself.

Be sure you understand the role of the:

p99 The Three Big Lifecycle Moments

Understand the role of init(), service() and doGet()/doPost().

p100 The service() method is always called in its own stack...

p101 Each request runs in a separate thread!

Check the confirmed errata for this page

This is a very important concept: there is only one instance of the servlet.

The Container (e.g. Tomcat) starts or finds a thread to invoke the service() method for each incoming client request.

One instance of the servlet—multiple threads. If you forget this, you'll code yourself into knots, and your web app won't work. So study these two pages and the diagrams on them until you get this.

p102 In the beginning: loading and initializing

To understand why the material on this page is important, consider a specific example: JDBCServlet_v2.java (my revised version of Sebesta's JDBC Example. In this code, the init() method established the connection with the database, and the doGet() method (invoked from the service() method) uses that connection. So it is crucial to understand the sequence of events, as shown in the black box on this page:

init() always completes before the first call to service()

But consider the question posed by the Flex Your Mind question: why do we need an init() method separate from the constructor? The question details give you a hint—you can get more hints by looking at the name of the object passed into init(), shown back on p. 98.

p103 Servlet Initialization: when an object becomes a servlet

This page—sort of—answers the question posed by the Flex Your Mind question on p. 102. The main point to understand here is to do initialization type stuff in the init() method, not in the constructor.

p104 What does 'being a servlet' buy you?

Read this page to understand what a ServletConfig and a ServletContext are for.

The "watch it" box on this raises an important issue—one that often confuses new Java programmers creating web apps. To understand this issue, first realize this:

Consider, for example, an online shopping application.

Photo of a Bedouin man in Israel wearing a Fez, May 13 2005. From Wikimedia Commons

Photo of a Bedouin man in Israel wearing a Fez, May 13 2005. Image is licensed from Wikimedia Commons.

p105 But a Servlet's REAL job is to handle requests.

So, a page where you need to fill in the details yourself. The answers are earlier in the chapter. Actually filling this in (either directly in the book, or on a separate piece of paper) will help you remember it. Plus, this is a reasonable exam question.

I'm surprised, though, that the servlet doesn't have its Fez, the way it does on pp. 103 and 104.

p106 Request and Response: the key to everything, and the arguments to service()

Check the confirmed errata for this page

The request and response objects are two of your main tools in doing Java Servlet programming, so spend some time getting to know their APIs. This page has a nice overview.

At this moment, most of this page be so much "blah blah ginger"—however, if you look back on this page from time-to-time as you go through the semester, you should find that more and more of the methods from the four Interfaces shown on this page are starting to become familiar. When you can look at this page, point to each of methods and describe a "situation in which is might be useful", then you've started to really understand how to build web apps in Java.

p107 There are no dumb questions
(about HttpServletRequest and HttpServlet Response)

This page should help you expand on your knowledge of

The book assumes you are already sort of familiar with UML diagrams. If you aren't—here's the short version

A 60-second intro to UML

To be honest, UML is one of those things that has come on the scene more recently that my last formal class in Software Engineering (a graduate class I took in 1986), so I'm still playing catch up—I haven't used UML in real-world project, so I can't really comment on it with any authority. Folks I've talked to that have used it on real projects are divided in their opinions.

Let's just say that as you go into job interviews you definitely should show some recognition on your face if someone mentions UML to you, and be familiar at least with the information in the 60-second intro given here. More information—and links to even more—can be found at the Wikipedia entry for UML.

p108 The HTTP request Method determines whether doGet() or doPost() runs

Ah—pp. 108-109 bring the return of the queen of sarcasm: hands-on-hips-lady! (See my comments about her first appearance on p. 47).

This is the first of eleven pages (pp. 108-118) on a theme: the eight HTTP methods, and GET vs. POST. You'll want to read these eight pages together. You may also want to review pp. 13-19, and the reading notes on those.

Note that Question 6 on last Spring's midterm exam was on the topic of pages 108-118.

p109 Actually, one or more of the other HTTP Methods might make a (brief) appearance on the exam.

Good to know about these, but not that important for our purposes.

p110 The difference between GET and POST

This page on the other hand, is more important to understand. In class, ask me, and I'll demonstrate how you can use a packet sniffer such as Ethereal to show the GET and POST requests generated by your browser.

p111 No, its not just about the size

It's important to understand the issues mentioned on this page:

But the big issue explored in the next few pages is idempotency. That's an important "concept" for you to have as a computer scientist.

Wikipedia has entries on idempotency both within mathematics and computer science—its the computer science definition that interests us more here. You may want to look over that page for some background before proceeding—or save that until after you've read pages 112-115.

p112 The story of the non-idempotent request
p113 Our story continues...

This illustrates very clearly what happens with a request that is NOT idempotent. From that, can you figure out what an idempotent request would be?

p114 Sharpen your pencil and Flex Your Mind

Check the confirmed errata for this page

Spend some time thinking about these two exercises before you move on.

p115 Being idempotent is GOOD (... no unwanted side effects!)

This page is as close as HFSJ gets to actually providing a definition of idempotency. If you still aren't sure what it means though, now is the time to read over the Wikipedia article.

p116 POST is not idempotent

Check the confirmed errata for this page

Actually, there are some subtle details in the "Bang" box on this page, and the "handwritten note" at the bottom of the page.

The authors write as if it were very simple:

GET is idempotent. POST is not.

But in fact, the situation is a bit more nuanced than that. What are the subtleties that this simplistic explanation overlooks?

Consider the following questions:

p117 What determines whether the browser sends a GET or POST request?

This page (and the one that follows) helps you understand how what you write in your HTML code determines whether the browser sends a GET or POST.

For the exams (and for sake of being able to write web apps) understand how to specify GET or POST in your HTML code.

p118 POST is NOT the default!

Check the confirmed errata for this page

From this page, understand the following:

p119 Sending and using a single parameter

This page expands a bit on the code for your Beer-v1 servlet from Chapter 3, and explains what was going on there. Compare it with the code on p. 120.

p120 Sending and using TWO parameters

As a challenge, you might take the code on this page and make a new version of your Beer-v1 and product servlets (the ones from Spring 2006 H02) and extend them to take two parameters. This will require changing all three components: Model, View and Controller. (@@@ Note to self—consider making an optional assignment along these lines.)

p121 You can have multiple values for a single parameter!

An important point! This one might show up on the exam. I probably would not ask you for the details of syntax, but I would expect the following:

As a challenge (similar to the challenge in the reading notes for p. 120) you might take the code on this page and make a new version of your Beer-v1 and product servlets (the ones from Spring 2006 H02) that allows selection of Beers (or your products) via a set of checkboxes—thus illustrating the use of returning multiple values for a single parameter. This will require changing all three components: Model, View and Controller. (@@@ Note to self—consider making an optional assignment along these lines—combine it with the one from p. 120).

p122 Beside parameters, what else can I get from a Request object?

The request object is what you have to work with when you are writing a Servlet. So the invitation on p. 122 is to spend some time understanding what you can do with it.

 

p123 There are no Dumb Questions (about Request object methods)

Check the confirmed errata for this page

Learn about

Regarding the box about getServerPort(), getLocalPort(), and getRemotePort()—this is one part that you can feel free to skip for purposes of CISC474. I'm skeptical about the last sentence anyway—I suspect that it contains a technical error (perpetuating a common misunderstanding about how TCP ports work)—but since it doesn't matter for purposes of CISC474, let's not worry about it for now.

p124 Review: servlet lifecycle and API
p125 Review: HTTP and HttpServletRequest

The bullet points in the left hand column of p. 124 are pretty much all things you should know before proceeding. I strongly encourage you to go over this point by point, and if anything is not clear, go back to the start of Chapter 4 and work through it again.

p126 So that's the Request... now let's see the Response

So now, pp 126-140 are all about the response, and probably should be read as a group.

p127 Using the response for I/O
p128 Imagine you want to send a JAR to the client...

These two pages explain why you might want to use the output stream for something other than sending back HTML. The example on p. 128 shows sending back a JAR file. However, understand:

Consider some ways in which CISC474 students of the past have made use of the technique illustrated here:

So the technique is very generally useful.

p129 Servlet code to download the JAR

In the code on this page, imagine "application/jar" being replaced with any MIME type—e.g. the MIME type for an MP3 file, or for an Excel spreadsheet.

This example shows serving up a file that already exists as a file in the web app's disk space. That may leave you wondering how you would do this if you were generating the file on the fly.

Howver, if you look more carefully into the code, you can begin to see how that might be done. The loop that serves up the file is just a plain old I/O loop that is copying bytes from source to destination. Those bytes could just as easily be generated by some function that you are calling.

The "There are no Dumb Questions" section on this page provides some insight into how you can locate an existing file relative to the web-app directory structure.

p130 Whoa. What's the deal with content type?
p131 There are no Dumb Questions (about content type)

All of this information is useful and important—and even this is not enough. Ultimately, you'll also need to take into account character sets as well.

So in addition to looking over this, you should read over Joel Spolsky's primer on character sets titled The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)

p132 You've got two choices for output: characters or bytes

Check the confirmed errata for this page

Related to the issue of character sets (see notes on p. 131) is the issue of how to write. As you may know, Java deals in Unicode, so writing characters and bytes are not (necessarily) going to result in the same output.

Fortunately, the sidebar on memorizing these methods does not apply to CISC474—it only applies to the SCWCDE exam, not to the exams in this course. The material in that sidebar is useful, though, if you are going to code up a web app that serves up a file.

p133 You can set response headers, you can add response headers

Read this page to learn the difference between adding a header and setting a header.

Note the limerick in the bottom right hand corner—this will help re-enforce the difference.

p134 But sometimes you just don't want to deal with the response yourself...
p135 (p. 134 continued)

This picture is important, because in a few pages, we are going to compare an constrast request "redirect" and request "dispatch". This picture shows "redirect"

p136 Servlet redirect makes the browser do the work

Check the confirmed errata for this page

Read this page to see the code that corresponds to the scenario on p. 134-135, and to understand relative vs. absolute URLs when using servlet redirect.

p137a You can't do a sendRedirect after writing to the response!
p137b sendRedirect() takes a String, NOT a URL object!

Two important bits of coding detail—read over them, and you'll avoid some common traps.

p138 A request dispatch does the work on the server side

This diagram is even more important than the one on pages 134-135, because this one (Request Dispatch) corresponds to a very typical way to build MVC-based web apps. Request Dispatch is how we process the request in the servlet, but hand off the processing of the response to a JSP.

p139 Redirect vs. Request Dispatch

Use the cartoons to help you remember

 

p140 Review: HttpServletResponse

Review the bullet points here—all of them are things you'll find useful when developing full-blown web apps.

p141 Coffee Cram (Mock Exam Chapter 4, Q1-Q3)

This is the first of eleven chapters (Chapters 4-14) that all end with multiple choice questions similar to those that might be on the SCWCDE Exam.

Not all of these questions are ones that I'd ask on a CISC474 exam. Some of them require knowledge that isn't even covered in the chapter, but is, instead, provided only in the API. The book's authors expect folks who are preparing for the exam to study that API as well as the textbook.

However, even in spite of that, I was surprised at how well I was able to do when I quizzed myself—even without looking at or studying the API in depth—just by using common sense and the general concept-level information about the Servlet life-cycle that was provided in the chapter.

So give these questions a try.

Note that some of the multiple choices questions are different from what you might be used to, in the sense that there can be more than one right answer. To get full credit, you have to choose all the correct answers and none of the incorrect answers. Watch for the words "Choose all that apply"

(In a sense, those questions are more like true/false—i.e. true or false, each of the following is a correct answer to the question.)

Question 1: I was able to get this one without even looking. I think you should be able to also. This one could be an exam question.

Question 2: For this one, I had to look in the chapter, but I found the answer easily. I'd encourage you to look for the answer too. However, I wouldn't ask this on an exam though.

Question 3: For this one, I had to look. I found it easily, but I wouldn't ask this on an exam.

p142 Coffee Cram (Mock Exam Chapter 4, Q4-Q7)

Question 4: I was able to get this one without looking. It is interesting to consider whether PUT should be considered idempotent or not. I had to guess, but I guessed correctly.

Question 5: I was unable to find the answer in the chapter precisely spelled out—hinted at yes, but not precisely given. This is one where I think you'll need to refer to the API to get the correct answer. I wouldn't ask this.

Question 6: I got this one easily, without looking. This could be an exam question.

Question 7: I was able to narrow it down to two on just common sense. Getting the final answer from among those two choices required me to look in the chapter.

p143 Coffee Cram (Mock Exam Chapter 4, Q8-Q10)

Question 8: This one should be easy, and is definitely a reasonable exam question.

Question 9: I was able to deduce "yes or no" for A through D easily from the general description of HttpServletRequest vs. ServletRequest given in the chapter (without having spent any time looking at the APIs in detail.)

For E, I had to guess, and I guessed wrong, so I would not ask you about that one.

However, in the large scheme of things, I'm not sure why this is important to memorize, so I wouldn't ask you about it (unless I gave you the API as a reference.)

Question 10: You should totally know this one. This one is definitely a reasonable CISC474 exam question.

p144 Coffee Cram (Mock Exam Chapter 4, Q1-Q3 answers)
p145 Coffee Cram (Mock Exam Chapter 4, Q4-Q7 answers)
p146 Coffee Cram (Mock Exam Chapter 4, Q8-Q10 answers)

Some of the answers given on these pages have some interesting comments beside them, so even if you don't try the questions for practice (which you totally should), look over the answers and the comments beside them anyway.


End of CISC474 reading notes for HFSJ, Chapter 4


Valid XHTML 1.1 Valid CSS!