当我读到有关servlet生命周期的书时,它说它首先调用服务方法,然后服务方法调用另一个方法来处理特定的HTTP请求(GET或POST)。但是当我尝试这个时,我发现在调用服务方法之前首先调用doGet或doPost方法。我的代码和结果如下,很多!
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");
}
}
结果:
init has been called
get has been called
service has been called
post has been called
service has been called
答案 0 :(得分:4)
你的书是对的。在您覆盖的service()
方法中,您在super.service()
电话之前呼叫System.out.println()
;正在从超类doPost()
的{{1}}方法调用doGet()
和service()
。尝试在调用HttpServlet
之前输出输出行,你会看到。
如果您从方法中移除super.service()
,则根本不会调用super.service()
或doPost()
;这就是为什么覆盖doGet()
通常不是一个好主意,除非你知道你在做什么,并且有充分的理由这样做。