【问题标题】:How getServletName() works in Java?getServletName() 如何在 Java 中工作?
【发布时间】:2014-09-25 13:22:19
【问题描述】:

出于好奇,我查看了 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();
}

任何人都可以告诉我这个..

【问题讨论】:

  • 这不是自称。 GenericServlet 调用的是 servletConfig.getServletName() 而不是 this.getServletName()。碰巧 GenericServlet 为了方便也实现了 ServletConfig 接口,但它不是 servletConfig。它通过它的 init(ServletConfig config) 方法获取 serveltConfig 对象。然后在 getServletName() 方法中,它只是充当代理将此调用传递给 config.getServletName() 方法。这里有什么不明白的地方??
  • 是的,你是对的@Gas,但我没有得到的是它如何返回 servlet 的名称,因为 ServletConfig 的 getServletName() 只是一个抽象方法。此外,如果我们在 GenericServlet 类中按住 ctrl+单击“sc.getServletName()”来查看它的实现,我们会再次使用相同的方法!我想知道本质上从哪里返回字符串(Servlet的名称)..

标签: servlets servletconfig


【解决方案1】:

javax.servlet.GenericServlet 实现了ServletConfig 接口,但它不包含ServletConfig 的实际实现。它通过container 提供的config 对象使用委托在调用init 方法时。

GenericServletServletConfig 对象(它是 tomcat 的 StandardWrapperFacade obj)作为 init(ServletConfig config) 方法的参数,并在调用时存储其对实例变量 config 的引用container

  • 初始化方法

     public void init(ServletConfig config) throws ServletException {
     this.config = config;//assign config to the instance variable
     this.init();
     }
    
  • 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
      }
     }
    


    因此,它不是在当前实例(this)上调用 getServletName() 而是在传递的 config 对象上调用它servlet container 初始化 servlet。


您还应该查看servlet Life-Cycle

为tomcatorg.apache.catalina.core.StandardWrapper提供了ServletConfig接口的实际实现。

更新:-

如果您想获取底层类的名称,那么您可以使用object.getClass().getName(); 方法。

【讨论】:

  • 谢谢@Vikrant 我也同样认为实际的实现必须在其他地方......正如你所清除的那样,它在 org.apache.catalina.core.StandardWrapper 中为 Tomcat 进行另一个调用到 getName() 以返回名称。 :) 我想以前我的问题被误解为调用是递归的,我之所以这么说是因为在 sc.getServletName() 上的 eclipse 中执行 ctrl+click 时,我采用了相同的方法!无论如何,谢谢:)
猜你喜欢
  • 2016-10-29
  • 2013-01-05
  • 2014-09-25
  • 2012-02-05
  • 1970-01-01
  • 2016-08-27
  • 1970-01-01
  • 1970-01-01
  • 2012-03-22
相关资源
最近更新 更多