Servlet从web.xml初始化数据库参数

时间:2016-09-30 10:23:31

标签: java xml servlets context-param

我的web应用程序中的context-params存在问题。我的方法

 getServletContext().getInitParameter("pass");

返回null。 这是我的web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Log4jWebDemo1</display-name>
<context-param>
    <param-name>log4j-config-location</param-name>
    <param-value>WEB-INF/log4j.properties</param-value>
</context-param>
    <context-param>
        <param-name>url</param-name>
        <param-value>dbc:postgresql://localhost/OlapTest</param-value>
    </context-param>
    <context-param>
        <param-name>name</param-name>
        <param-value>org.postgresql.Driver</param-value>
    </context-param>
    <context-param>
        <param-name>usr</param-name>
        <param-value>postgres</param-value>
    </context-param>
    <context-param>
        <param-name>pass</param-name>
        <param-value>admin</param-value>
    </context-param>
  <servlet>
    <servlet-name>Hello World</servlet-name>
    <servlet-class>pl.javastart.servlets.HelloWorldServlet</servlet-class>

  </servlet>
  <servlet-mapping>
    <servlet-name>Hello World</servlet-name>
    <url-pattern>/test</url-pattern>
  </servlet-mapping>
</web-app>

我的servlet:

public class HelloWorldServlet extends HttpServlet {
       private static final long serialVersionUID = 1L;
       private String url2 = ""; 
       private String driver = ""; 
       private String username = ""; 
       private String password = ""; 

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        PrintWriter out = response.getWriter();
        url2 = getServletContext().getInitParameter("url");
        driver = getServletContext().getInitParameter("name");
        username = getServletContext().getInitParameter("usr");
        password = getServletContext().getInitParameter("pass");

        DatabaseHandling d1 = new DatabaseHandling(driver,url2,username,password);

        d1.createConnection(out);

        }
}

执行我的应用程序后,它会抛出

  

显示java.lang.NullPointerException

1 个答案:

答案 0 :(得分:1)

导致NullPointerException异常的可能性很少

  1. 您的类路径中未添加PostgresSQl驱动程序( jar文件)库。
  2. 您需要共享DatabaseHandling类,以便检查为与DB连接而编写的代码。
  3. 更改web.xml,如下所示:

    <context-param> <param-name>url</param-name> <param-value>jdbc:postgresql://localhost/OlapTest</param-value> </context-param>

  4. 缺少

    J 。检查错误 dbc