This week's giveaway is in the EJB and other Java EE Technologies forum. We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line! See this thread for details.
I am modifying code which uses service() in its servlets. In the past I have used doPost or doGet. Could someone please explain the pros and cons of using service() instead of one of the other methods?
In his book CORE SERVLETS AND JAVA SERVER PAGES ( http://www.amazon.com/exec/obidos/ASIN/0130893404/electricporkchop ) Marty Hall says: Don't override service()! If you need to execute the same logic when either POST or GET methods are invoked, just make one method call the other one where all the logic is. I left the book at the office so I can't quote all the reasons why (plenty), but I just remember that he convinced me when I read it months ago
Tony Alicea Senior Java Web Application Developer, SCPJ2, SCWCD
Judy, The main reason not to override doPost method is 'we can't add support for other services latter'. Actually doPost is like a 'router'. Depending upon the type of HTTP request (HEAD/GET/PUT/POST/TRACE/OPTIONS), it calls the corresponding do*** methods. (doGet/doPut/doPost...etc). So when we override this method we basically loose this feature. There are some cases which may convince this concept. 1. When a HTTP request asks for a page with some condition in its header, like 'give me this page if it is modified since ---DATE--'. So what the first invoked service method does is , it automatically calls the 'getLastModified' method of this servlet , which returns the time in millisecs, and compares the HTTP request's 'If-modified-since' header's value and act accordingly. 2. When a Http request of HEAD comes. which means the servlet need not send the content but only the headers of the page. This happens when link validators check a page if it is working like that. They just ask for HEAD and if they get any response, that means the link is ok. Just to check the link we needn't download the WHOLE page isn't? So for this type of situations, the doPost does the exact work of calling the 'doGet' method but extracts the Headers alone and send to the request. So basically we want to keep the above said 'special features' of service method and make use of them. THis is the reason behind it. regds maha anna
The last response stated "The main reason not to override doPost method..." but I think the writer meant to say "The main reason not to overriide the "service" method..." It's the service method that calls the other doXxx methods.
seems to me that you can call super from your inherited service method. while there is no reason to override service, if a request has been performed, it may be necessary to do so if the first page itself is a servlet which is in charge of redirecting info to different jsp pages. just read all this stuff - i am new in this area.