Difference b/w <context-param> and <init-param>

本小妞迷上赌 提交于 2019-11-27 13:34:56

问题


DD elements <context-param> and <init-param> both can be retrieved by the getInitParameter() method, in the servlet code.

Now the question is, how does it differentiate <context-param> and <init-param>?


回答1:


Servlet init parameters are for a single servlet only. Nothing outside that servlet can access that. It is declared inside the <servlet> tag of Deployment Descriptor, on the other hand context init parameter is for the entire web application. Any servlet or JSP in that web application can access context init parameter. Context parameters are declared in a tag <context-param> directly inside the <web-app> tag.

The methods for accessing context init parameter is

getServletContext().getInitParameter("name"); 

whereas the method for accessing servlet init parameter is

getServletConfig().getInitParameter("name");



回答2:


As explained by Adeel Ansari, here, it depends on what object are you invoking the method getInitParameter() in the servlet code.

All servlets extends from and hence are instance of GenericServlet.

.

DD elements <context-param> can be retrieved by:

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

.

DD elements <init-param> both can be retrieved by:

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() ). Hence you can also get DD elements <init-param> directly by:

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.



来源:https://stackoverflow.com/questions/2069902/difference-b-w-context-param-and-init-param

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!