请教一下,getServletContext和getServletConfig都有getInitParameter的方法,
但是他们有什么不同呢?
我在web.xml中web-app根下定义了一个参数P1,
然后在web.xml中的HelloServlet段中也定义了一个参数P1,
在HelloServlet分别作如下输出
String s1 = getServletConfig().getInitParameter("P1");
String s2 = getServletContext().getInitParameter("P1");
String s3 = getServletConfig().getServletContext().getInitParameter("P1");
String s4 = getInitParameter("P1");
发现结果如下
s1:This is the servlet value
s2:This Is web-app Value
s3:This Is web-app Value
s4:This is the servlet value
我实在是不能明白为什么,请高手赐教
下附代码段
===========================
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
...
<context-param>
<param-name>P1</param-name>
<param-value>This Is web-app Value</param-value> </context-param>
...
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>suman.Servlet.HelloServlet</servlet-class>
<init-param>
<param-name>P1</param-name>
<param-value>This is the servlet value</param-value> </init-param>
</servlet>
...
</web-app>
==============================
public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
...
String s1 = getServletConfig().getInitParameter("P1");
String s2 = getServletContext().getInitParameter("P1");
String s3 = getServletConfig().getServletContext().getInitParameter("P1");
String s4 = getInitParameter("P1");
out.println("SumanChina_DoGet");
out.println("<br>");
out.println("s1:"+s1+"<br>");
out.println("s2:"+s2+"<br>");
out.println("s3:"+s3+"<br>");
out.println("s4:"+s4);
...
}
}
getServletContext().相当于Application
getServletConfig().某个servlet的配置
getServletContext()取得的是<context-param>配置的参数
getServletConfig()取得的是<servlet><init-param>配置的参数
String s1 = getServletConfig().getInitParameter("P1"); //取得是servlet的初始值
String s2 = getServletContext().getInitParameter("P1"); //取得是application中的初始值
String s3 = getServletConfig().getServletContext().getInitParameter("P1"); //取得是application中的初始值
String s4 = getInitParameter("P1"); //取得是servlet的初始值
getServletContext()应用于整个web App,而getServletConfig()仅应用于当前Servlet。
但是ServletConfig对象拥有ServletContext的引用。所以可以通过getServletConfig()来获得web App的初始值。
摘自:http://bbs.csdn.net/topics/220045809
另外,还有一位网友遇到 Servlet 中使用 getServletContext() 不起作用、报错的现象