1

当我阅读有关 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
4

1 回答 1

4

你的书是对的。在您的覆盖service()方法中,您在调用super.service()之前System.out.println()调用;doPost()并从超类的方法中doGet()调用。尝试将输出行放在调用之前,您会看到。service()HttpServletsuper.service()

如果您super.service()从您的方法中删除,则根本不会调用,doPost()doGet()不会调用;这就是为什么重写通常不是一个好主意,service()除非您知道自己在做什么并且有充分的理由这样做。

于 2013-01-13T06:18:56.073 回答