gpt4 book ai didi

java - 为什么我们不能调用 servlet 构造函数而不是 init 方法来初始化配置参数?

转载 作者:搜寻专家 更新时间:2023-10-30 21:20:17 29 4
gpt4 key购买 nike

我想知道为什么我们不调用 servlet 构造函数而不是 init 方法来初始化配置参数。

谢谢

最佳答案

This thread should clarify the differences.

引用一篇更有启发性的帖子:

The init() method is typically used to perform servlet initialization--creating or loading objects that are used by the servlet in the handling of its requests. Why not use a constructor instead? Well, in JDK 1.0 (for which servlets were originally written), constructors for dynamically loaded Java classes (such as servlets) couldn't accept arguments. So, in order to provide a new servlet any information about itself and its environment, a server had to call a servlet's init() method and pass along an object that implements the ServletConfig interface. Also, Java doesn't allow interfaces to declare constructors. This means that the javax.servlet.Servlet interface cannot declare a constructor that accepts a ServletConfig parameter. It has to declare another method, like init(). It's still possible, of course, for you to define constructors for your servlets, but in the constructor you don't have access to the ServletConfig object or the ability to throw a ServletException.

关于java - 为什么我们不能调用 servlet 构造函数而不是 init 方法来初始化配置参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2381976/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com