How to retrieve <servlet><init-param> value from web.xml in Servlet?

时间秒杀一切 提交于 2019-12-18 07:01:02

问题


I need to retrieve init-param value from xml to Servlet i used following code

<servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>LoginServlet</servlet-class>
    <init-param>
        <param-name>jdbcDriver</param-name>
        <param-value>com.mysql.jdbc.Driver</param-value>
    </init-param>
</servlet>

servlet code

public void init(ServletConfig config) throws ServletException {
    super.init(config);
    System.out.println(config.getInitParameter("jdbcDriver"));
}

But It displayed null .. could any one help me to do that . thanks in advance


回答1:


I can't see a single reason, why you have to override your init(ServletConfig sc) method, since you can always get your ServletConfig by calling your inherited getServletConfig() method.

System.out.println(getServletConfig().getInitParameter("jdbcDriver"));



回答2:


If you have custom initialization work to do, override the no-arg init() method, and forget about init(ServletConfig). Is it ok to call getServletConfig() method inside the no-arg init() method? Yes, an instance of ServletConfig has already been saved by superclass GenericServlet.

http://javahowto.blogspot.com/2006/06/common-mistake-in-servlet-init-methods.html

It is always good to use packages for classes. It enables clear demarcation.




回答3:


um... it should work. Are you calling the code in LoginServlet? And the

<servlet-class>LoginServlet</servlet-class> 

is not in any package?



来源:https://stackoverflow.com/questions/8682740/how-to-retrieve-servletinit-param-value-from-web-xml-in-servlet

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