Question 19 of 60
Following is the code for TestServlet . Assuming that it is not preloaded or preinitialized, which of the given statements about it are correct?
(The statements are regarding the methods defined in this class.)
select any 2
a For any and every HTTP request, at the most 2 of it's methods will be called.
b For any and every request, atleast 1 of it's methods will be called.
c For any and every request, service() will be called.
d For an HTTP PUT request, none of it's methods will be called.
e For an HTTP PUT request, it'll throw an exception.
answer is bc.
but if we send any request for which doXXX method is not defined then it throws some exception.
am I correct in this?
if above two statements are true then does that mean we can avoid exception if we add the following two lines in every class?
public void service(HttpServletRequest req, HttpServletResponse res)
First of all you can not override service method....
I think we can override service() method.
See HttpServlet api, it is not declared final.
Inorder to get default service method implementation behavior, we need to call super.service(request,response) in the overridden method.
In other words, your servlet class that extends HttpServlet should not override the service(...) method because:
You can add support for different behaviors for different request types by overriding the appropriate doXXX(...) method. This makes sense since a servlet should not return a "successful" response (i.e. status code in the 200 range) for a DELETE request unless it actually did delete the requested resource.
The default service(...) method supports modification dates (i.e.conditional GET requests) by using the getLastModified(HttpServletRequest) method (which you can override to improve performance).
You get automatic support for TRACE, OPTIONS, and HEAD requests (although you can override the doHead(...) method (in servlets 2.3+) to improve performance).
you could override service directly (to "improve" performance by reducing the number of method calls) and include the appropriate logic to replace the aforementioned functionality, but why re-invent the wheel?
And if performance is really your primary concern, never "micro-optimize" before profiling. Chances are, the code you've written has some bottlenecks that make the performance impact of these extra method calls negligible. As a matter of fact, the code you write to replace the functionality you are losing might just contain some of these bottlenecks.