[英]can't read context params from web.xml
我正在使用在Tomcat 7.0.41中運行的NetBeans編寫J2EE Web應用程序。 我創建了一個部署描述符web.xml,其中包含四個上下文參數。 我創建了一個擴展HttpServlet的類。 在該類的init方法中,當我從ServletConfig實例調用getInitParameterNames時,我得到一個空的枚舉。 最終,我懷疑Tomcat根本沒有讀取web.xml文件,因為我不得不訴諸使用@WebServlet注釋甚至到達Servlet。 誰能建議我為什么無法訪問上下文參數和/或Tomcat為什么不讀取web.xml文件?
這是web.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<context-param>
<param-name>preptimeminutes</param-name>
<param-value>60</param-value>
</context-param>
<context-param>
<param-name>preptimehours</param-name>
<param-value>0</param-value>
</context-param>
<context-param>
<param-name>servings</param-name>
<param-value>1</param-value>
</context-param>
<context-param>
<param-name>calories</param-name>
<param-value>100</param-value>
</context-param>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
這是init方法的代碼:
@Override
public void init(ServletConfig servletConfig) throws ServletException
{
int preptemp;
String tempString1, tempString2;
Enumeration<String> e = servletConfig.getInitParameterNames();
this.servletConfig = servletConfig;
servletContext = servletConfig.getServletContext();
try
{
while(e.hasMoreElements())
{
servletContext.log(e.nextElement());
}
} ...
}
謝謝,
傑森·馬佐塔(Jason Mazzotta)
似乎您想讀取ServletContex
參數(用於整個應用程序的參數),但最終卻要讀取ServletConfig
(用於特定servlet的參數)。
另一個潛在的問題是您要覆蓋init(ServletConfig)
而不是init()
。 第一個方法不應被覆蓋,因為它可以處理許多Servlet生命周期任務,例如將Servlet添加到可用的Servlet池中。 如果要在初始化過程中添加一些內容,則應重寫init()
方法,該方法稍后由init(ServletConfig)
調用。
所以嘗試像
@Override
public void init() throws ServletException
{
ServletContext servletContext = getServletContext();
Enumeration<String> e = servletContext.getInitParameterNames();
try
{
while(e.hasMoreElements())
{
servletContext.log(e.nextElement());
}
} ...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.