config.getInitParameter always return null

拈花ヽ惹草 提交于 2019-12-30 09:42:11

问题


Why does config.getInitParameter(String) always return null in the following code example?

public void init(ServletConfig config) throws ServletException
{
    super.init(config);
    filename = config.getInitParameter("addressfile");

This is web.xml file

<servlet>
<servlet-name>ListManagerServlet</servlet-name>
<servlet-class>savva.listmanagerservlet.ListManagerServlet</servlet-class>
<init-param>
    <param-name>addressfile</param-name>
    <param-value>d:\temp\demo.txt</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ListManagerServlet</servlet-name>
<url-pattern>/ListManagerServlet</url-pattern>
</servlet-mapping>

UPD: Eclipse EE Indigo, Java 1.6, Tomcat 7.0


回答1:


The canonical way is to just use the inherited GenericServlet#getInitParameter() in the argumentless init() method (and remove any init(config) method).

@Override
public void init() throws ServletException {
    filename = getInitParameter("addressfile");
}

If that still doesn't work, then your web.xml is not properly been deployed, or you have a typo in the parameter name, or you actually accessed a different instance variable than filename to use/test it.




回答2:


Ensure your servlet is calling super.init(config) on its init method, else it won't work.




回答3:


Make sure you have really deployed the proper web.xml. Also check with config.getInitParameterNames() what parameters have been found.




回答4:


It's never a good idea to override the init(config) method. Instead use the provided init() convenience method and do a getServletConfig() to get the configuration parameters:

http://docs.oracle.com/javaee/1.2.1/api/javax/servlet/GenericServlet.html#init() http://docs.oracle.com/javaee/1.2.1/api/javax/servlet/GenericServlet.html#getServletConfig()




回答5:


If use the IDE STS4, checkout if annotation on the class name exists, use BOTH "annotation" and "web.xml" may cause the value null.



来源:https://stackoverflow.com/questions/8401851/config-getinitparameter-always-return-null

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