Skip to Content
Head First Servlets and JSP, 2nd Edition
book

Head First Servlets and JSP, 2nd Edition

by Bryan Basham, Kathy Sierra, Bert Bates
March 2008
Intermediate to advanced
911 pages
20h 31m
English
O'Reilly Media, Inc.
Content preview from Head First Servlets and JSP, 2nd Edition

The Three Big Lifecycle Moments

1 init()

When it’s called

The Container calls init() on the servlet instance after the servlet instance is created but before the servlet can service any client requests.

What it’s for

Gives you a chance to initialize your servlet before handling any client requests.

Do you override it? Possibly.

If you have initialization code (like getting a database connection or registering yourself with other objects), then you’ll override the init() method in your servlet class.

2 service()

When it’s called

When the first client request comes in, the Container starts a new thread or allocates a thread from the pool, and causes the servlet’s service() method to be invoked.

What it’s for

This method looks at the request, determines the HTTP method (GET, POST, etc.) and invokes the matching doGet(), doPost(), etc. on the servlet.

Do you override it?

No. Very unlikely.

You should NOT override the service() method. Your job is to override the doGet() and/or doPost() methods and let the service() implementation from HTTPServlet worry about calling the right one.

3 doGet() and/or doPost()

When it’s called

The service() method invokes doGet() or doPost() based on the HTTP method (GET, POST, etc.) from the request.

(We’re including only doGet() and doPost() here, because those two are probably the only ones you’ll ever use.)

What it’s for

This is where your code begins! This is the method that’s responsible for whatever the heck your web app is supposed to be DOING.

You can call ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Head First Java, 2nd Edition

Head First Java, 2nd Edition

Kathy Sierra, Bert Bates
Head First Java, 3rd Edition

Head First Java, 3rd Edition

Kathy Sierra, Bert Bates, Trisha Gee
Learning Java, 6th Edition

Learning Java, 6th Edition

Marc Loy, Patrick Niemeyer, Daniel Leuck

Publisher Resources

ISBN: 9780596516680Errata PageSupplemental Content