为什么我们不能调用servlet构造函数而不是init方法来初始化配置参数? [英] Why can not we call servlet constructor instead of init method to initialize the config parameters?

查看:432
本文介绍了为什么我们不能调用servlet构造函数而不是init方法来初始化配置参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I like to know why dont we call servlet constructor instead of init method to initialize the config parameters.

THanks

推荐答案

此主题应该澄清差异。

从一个更有启发性的帖子中引用:

Quoting from one of the more illuminating posts:


init()方法通常用于
执行servlet
初始化 - 创建或加载servlet
在处理其请求时使用的
对象。为什么
不使用构造函数?好吧,JDK 1.0中的
(最初编写的servlet是
),
动态加载的Java类(例如
作为servlet)的构造函数无法接受
参数。因此,为了提供
新servlet有关
本身及其环境的任何信息,服务器
必须调用servlet的init()方法
并传递一个对象
实现了ServletConfig
接口。此外,Java不允许
接口声明构造函数。
这意味着
javax.servlet.Servlet接口不能
声明一个接受
ServletConfig参数的构造函数。它必须
声明另一个方法,比如init()。
当然,你可以为
定义
servlet的构造函数,但在构造函数中你
无法访问ServletConfig
对象或抛出
ServletException的能力。

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.

这篇关于为什么我们不能调用servlet构造函数而不是init方法来初始化配置参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆