在学习ServletConfig的过程中,出现一个问题让我始终无法理解,在折腾了一中午之后终于明白是自己太蠢。
首先,先大致提一下ServeletConfig配置
要取到位于XML中的值,例如
<init-param>
<param-name>head</param-name>
<param-value>a</param-value>
</init-param>
<init-param>
<param-name>header</param-name>
<param-value>b</param-value>
</init-param>
首先第一种方法
public void init(ServletConfig config) throws ServletException{
this.config = config;
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String paramValue = config.getInitParameter("head");
}
类似这要就能取到了,还有一种一次性全取到
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
Enumeration<String> enumss = config.getInitParameterNames();
while(enumss.hasMoreElements()){
String paramName = enumss.nextElement();
String paramValue = config.getInitParameter(paramName);
System.out.println(paramValue);
}
}
有点像js里面的getElementBytagName,然后在获取param-name标签中的值,再使用getInitParameter。
另外一种是直接调用父类方法将ServletConfig实例化
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
config = getServletConfig();
}
那么问题来了,config并不能取到所需要的值。问题就在于在父类中
getServletConfig(){
return config;
}
init(ServletConfig config){
this.config = config;
}
在上面的代码中,我重写了init()方法,因此无法取得config。这个地方的重点在于一般情况下父类是没办法取到子类的方法的,因此需要删去代码中的init()方法。