GenericServlet 中 getServletContext() 的递归
Recursion in getServletContext() in GenericServlet
下面是 GenericServlet class,
中的 2 个方法
public ServletConfig getServletConfig() {
return this.config;
}
public ServletContext getServletContext() {
return getServletConfig().getServletContext(); // is this RECURSION?
}
其次,这个方法getServletContext()最后会是什么returns?
不,这不是递归,因为方法中的 getServletContext()
调用是在 SevletConfig
对象上调用的,而 而不是 是在 servlet 本身上调用的。
它看起来像递归的原因是 GenricServlet
实现了 ServletConfig
并公开了所有方法该 接口 本身,但它通过将所有这些调用委托给由其实例成员变量 config
.
持有的 ServletConfig
对象来实现
这样做是为了方便在其 doGet()
、doPosts()
方法中使用 servlet 自己的 ServletConfig
。例如,servlet 想要读取其在 web.xml 中定义的初始化参数,在带有 <init-param>
的 <servlet>
标签中。
那就不这样做了
out.write(getServletConfig().getInitParameter("adminEmail"));
servlet 可以直接调用这个
out.write(getInitParameter("adminEmail"));
同样的 shorthand 也适用于 getServletContext()
。如果 GenericServlet
class 没有实现 ServletConfig
你将不得不到处调用 getServletConfig().getServletContext()
。
But GenericServlet implements ServletConfig. Hence again, the call will be on GenericServlet's method
不,这是递归
public String toString() {
return toString(); // BAD! WhosebugError
}
这不是
public String toString() {
return instanceVar.toString(); // OK
}
仅仅因为方法名称相同,并不能递归。
您必须在 哪个 对象上查看该方法被调用。在 servlet 的情况下,第一次调用是在 GenericServlet
对象(或者技术上是它的子 class)上,第二次调用是在它的 config
成员变量上——一个 ServletConfig
对象。
下面是 GenericServlet class,
中的 2 个方法 public ServletConfig getServletConfig() {
return this.config;
}
public ServletContext getServletContext() {
return getServletConfig().getServletContext(); // is this RECURSION?
}
其次,这个方法getServletContext()最后会是什么returns?
不,这不是递归,因为方法中的 getServletContext()
调用是在 SevletConfig
对象上调用的,而 而不是 是在 servlet 本身上调用的。
它看起来像递归的原因是 GenricServlet
实现了 ServletConfig
并公开了所有方法该 接口 本身,但它通过将所有这些调用委托给由其实例成员变量 config
.
ServletConfig
对象来实现
这样做是为了方便在其 doGet()
、doPosts()
方法中使用 servlet 自己的 ServletConfig
。例如,servlet 想要读取其在 web.xml 中定义的初始化参数,在带有 <init-param>
的 <servlet>
标签中。
那就不这样做了
out.write(getServletConfig().getInitParameter("adminEmail"));
servlet 可以直接调用这个
out.write(getInitParameter("adminEmail"));
同样的 shorthand 也适用于 getServletContext()
。如果 GenericServlet
class 没有实现 ServletConfig
你将不得不到处调用 getServletConfig().getServletContext()
。
But GenericServlet implements ServletConfig. Hence again, the call will be on GenericServlet's method
不,这是递归
public String toString() {
return toString(); // BAD! WhosebugError
}
这不是
public String toString() {
return instanceVar.toString(); // OK
}
仅仅因为方法名称相同,并不能递归。
您必须在 哪个 对象上查看该方法被调用。在 servlet 的情况下,第一次调用是在 GenericServlet
对象(或者技术上是它的子 class)上,第二次调用是在它的 config
成员变量上——一个 ServletConfig
对象。