when i read book regarding the life cycle of servlet, it says that it first calls the service method, then the service method calls another method to handle specific HTTP request(GET or POST).But when I try this out, I find that the doGet or doPost method are firstly called before the service method being called. My Code and result are as follows, thx a lot!
public class Main extends HttpServlet {
@Override
public void init() throws ServletException {
// TODO Auto-generated method stub
super.init();
System.out.println("init has been called");
}
@Override
protected void service(HttpServletRequest arg0, HttpServletResponse arg1)
throws ServletException, IOException {
// TODO Auto-generated method stub
super.service(arg0, arg1);
System.out.println("service has been called");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("get has been called");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("post has been called");
}
}
result:
init has been called
get has been called
service has been called
post has been called
service has been called
Your book is correct. In your overridden service()
method you're calling super.service()
before the System.out.println()
call; doPost()
and doGet()
are being called from the service()
method of the superclass HttpServlet
. Try putting the output line before the call to super.service()
and you'll see.
If you remove super.service()
from your method, neither doPost()
nor doGet()
will be called at all; this is why it's generally not a good idea to override service()
unless you know what you're doing and have a good reason to do so.