Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
36
Chapter 2 First Servlets
console. For examples of these settings, see Section 2.7 (An Example Using
Initialization Parameters).
The second thing to note about the second version of 
init
 is that the first
line of the method body is a call to 
super.init
. This call is critical! The
ServletConfig
 object is used elsewhere in the servlet, and the 
init
 method
of the superclass registers it where the servlet can find it later. So, you can
cause yourself huge headaches later if you omit the 
super.init
 call.
Core Approach
If you write an 
init
 method that takes a 
ServletConfig
 as an 
argument, 
always
 call 
super.init
 on the first line.
The service Method
Each time the server receives a request for a servlet, the server spawns a new
thread and calls 
service
. The 
service
 method checks the HTTP request
type (
GET
, 
POST
, 
PUT
, 
DELETE
, etc.) and calls 
doGet
, 
doPost
, 
doPut
, 
doDe 
lete
, etc., as appropriate. Now, if you have a servlet that needs to handle
both 
POST
 and 
GET
 requests identically, you may be tempted to override 
ser 
vice
 directly as below, rather than implementing both 
doGet
 and 
doPost
.
public void service(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Servlet Code
}
This is not a good idea. Instead, just have 
doPost
 call 
doGet
 (or vice
versa), as below.
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Servlet Code
}
public void doPost(HttpServletRequest request,
 HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
Although this approach takes a couple of extra lines of code, it has five
advantages over directly overriding 
service
:
Second edition of this book: www.coreservlets.com; Sequel: www.moreservlets.com.
Servlet and JSP training courses by book's author: courses.coreservlets.com.






footer




 

 

 

 

 Home | About Us | Network | Services | Support | FAQ | Control Panel | Order Online | Sitemap | Contact

jsp web hosting

 

Our partners: PHP: Hypertext Preprocessor Best Web Hosting Java Web Hosting Jsp Web Hosting Cheapest Web Hosting

Visionwebhosting.net Business web hosting division of Web Design Plus. All rights reserved