简体   繁体   English

差异b / w <context-param>和<init-param>

[英]Difference b/w <context-param> and <init-param>

DD elements <context-param> and <init-param> both can be retrieved by the getInitParameter() method, in the servlet code. DD元素<context-param><init-param>都可以通过servlet代码中的getInitParameter()方法检索。

Now the question is, how does it differentiate <context-param> and <init-param> ? 现在的问题是,它如何区分<context-param><init-param>

Servlet init parameters are for a single servlet only. Servlet init参数仅适用于单个servlet。 Nothing outside that servlet can access that. 该servlet之外没有任何东西可以访问它。 It is declared inside the <servlet> tag of Deployment Descriptor, on the other hand context init parameter is for the entire web application. 它在Deployment Descriptor的<servlet>标记内声明,另一方面, 上下文init参数用于整个Web应用程序。 Any servlet or JSP in that web application can access context init parameter . 该Web应用程序中的任何servlet或JSP都可以访问上下文init参数 Context parameters are declared in a tag <context-param> directly inside the <web-app> tag. 上下文参数直接在<web-app>标记内的标记<context-param>中声明。

The methods for accessing context init parameter is 访问上下文init参数的方法是

getServletContext().getInitParameter("name"); 

whereas the method for accessing servlet init parameter is 而访问servlet init参数的方法是

getServletConfig().getInitParameter("name");

As explained by Adeel Ansari, here , it depends on what object are you invoking the method getInitParameter() in the servlet code. 正如Adeel Ansari所解释的,这取决于你在servlet代码中调用getInitParameter()方法的对象。

All servlets extends from and hence are instance of GenericServlet . 所有servlet都是从GenericServlet扩展而来的。

.

DD elements <context-param> can be retrieved by: DD元素<context-param>可以通过以下方式检索:

ServletContext context = this.getServletContext();
String paramValue = context.getInitParamter("paramName");

.

DD elements <init-param> both can be retrieved by: DD元素<init-param>都可以通过以下方式检索:

ServletConfig config = this.getServletConfig();
String paramValue = config.getInitParamter("paramName");

Also note that since GenericServlet class implements ServletConfig interface, your servlet class is also ServletConfig (implies this = this.getServletConfig() ). 另请注意,由于GenericServlet类实现了ServletConfig接口,因此您的servlet类也是ServletConfig(暗示this = this.getServletConfig() )。 Hence you can also get DD elements <init-param> directly by: 因此,您还可以通过以下方式直接获取DD元素<init-param>

String paramValue = this.getInitParamter("paramName");

.

You can try this by having same param-name in both DD elements with different values and then print it in your servlet. 您可以通过在具有不同值的两个DD元素中使用相同的param-name来尝试此操作,然后将其打印在servlet中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM