Saturday, February 2, 2013

Head First Servlets and JSP: Chapter 3 & 4 MVC & Request-Response

When we work with servlets we should know these important interfaces and classes



and usually the servlet extends HttpServlet

Servlet Lifecycle
the life cycle is very easy, the servlet is either initialized or doesnt exist.


to understand more, the Container does the following


Firstly the container will load the servlet class,
then it will call the default constructor
then it will call the init() method
then service()
and when it finds appropriate it calls the destroy()



very important to understand that the container load only one instance of each servlet (there is a case with multiple instances with SingleThreadModel we will talk about it later), and create one thread for each request.



2 Important objects created by the container and passed to the servlet
1- ServletConfig: each servlet has one ServletConfig object
2- ServletContext: each web application has one ServletContext object (should be called AppContext)

Init() and constructor
as you can see the container calls the constructor then the Init() method. the question here is why we have a constructor and Init() methods, why dont we have just the constructor.

The first important thing, the init() method takes a parameter which is ServletConfig, which is created by the container and passed to the servlet.
you can say that we can build a constructor with argument why dont we do that. Actually the Container create the servlet class dynamically using reflection, in JDK 1.0 (when the Servlet was created) we werent be able to create a class dynamically using a constructor with argument, Thats why designers added the Init() method. the second reason, you want to force the inherited class to implement the Init() method, you cannot FORCE THE INHERITED CLASS TO IMPLEMENT A CONSTRUCTOR.

Request & Response





GET & POST
as we know Post has body and it is not idempotent
Get has no body and it is Idempotent

Redirect vs Dispatch
in redirect you send the response to the client with 301, the client send another request.
with dispatch you do the things on the server side:

response.sendRedirect()

or



No comments:

Post a Comment