Shu*_*Roy 0 servlets servletconfig
出于好奇,我查看了 HttpServlet 类的代码,发现它的父类“GenericServlet”定义了在接口“ServletConfig”中声明的方法“getServletName()”。但是,如果 ServletConfig 的对象“sc”不为空,GenericServlet 的 getServletName() 方法会调用“sc.getServletName()”。我无法理解这个东西是如何工作的,因为当我在 eclipse 中按 ctrl+click 来查看该方法的实现时,它似乎在调用自己!HttpServlet 类中也没有覆盖实现!
这是 GenericServlet 实现的快照:
public String getServletName() {
ServletConfig sc = getServletConfig();
if (sc == null) {
throw new IllegalStateException(
lStrings.getString("err.servlet_config_not_initialized"));
}
return sc.getServletName();
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以在这方面启发我..
javax.servlet.GenericServlet实现了ServletConfig接口,但它不包含 的实际实现。ServletConfig它通过使用config对象使用委托,该对象由container调用init方法的while提供。
GenericServlet将ServletConfig对象(它是StandardWrapperFacadetomcat的obj )作为init(ServletConfig config)方法的参数,并config在调用时存储其对实例变量的引用container。
初始化方法
public void init(ServletConfig config) throws ServletException {
this.config = config;//assign config to the instance variable
this.init();
}
Run Code Online (Sandbox Code Playgroud)getServletName 方法
public String getServletName() {
ServletConfig sc = getServletConfig();//returns the ref of instance variable i.e. config
if (sc == null) {
throw new IllegalStateException(
lStrings.getString("err.servlet_config_not_initialized"));
}
return sc.getServletName();//call method on config object
}
}
Run Code Online (Sandbox Code Playgroud)
因此,它不是getServletName()在当前实例(this)上调用它,而是在初始化 servlet 时config传递的对象上调用它servlet container。
您还应该查看servlet Life-Cycle。
为tomcatorg.apache.catalina.core.StandardWrapper提供了ServletConfig接口的实际实现。
更新:-
如果您想获取基础类的名称,则可以使用object.getClass().getName();方法。
| 归档时间: |
|
| 查看次数: |
1617 次 |
| 最近记录: |