JavaEE / Tomcat 9.0.0 / IntellijIdea 2016.2:java.sql.SQLException:无法创建类''用于连接网址' null'

时间:2016-09-08 19:35:17

标签: java tomcat java-ee intellij-idea

我的项目中的连接器存在问题。我已经在Tomcat的lib中添加了MySQL连接器,并且还在IntellijIDEA中添加了项目的路径,但问题仍然存在。 stackoverlow中旧版本的答案在这里没有用。  这是项目类:

的web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app 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_1.xsd"
           version="3.1">

    <resource-ref>
        <description>DB Connection</description>
        <res-ref-name>jdbc/library</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
    </resource-ref>

    <context-param>
        <param-name>javax.faces.CONFIG_FILES</param-name>
        <param-value>/WEB-INF/context.xml</param-value>
    </context-param>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>

</web-app>

context.xml中

<?xml version="1.0" encoding="UTF-8"?>
<Context path="/myApp" docBase="myApp"
         crossContext="true" reloadable="true" debug="1">
    <Resource name="jdbc/library"
              global="jbc/library"
              auth="Container"
              type="javax.sql.DataSource"
              initialSize="10"
              maxTotal="100"
              maxIdle="30"
              maxWaitMillis="10000"
              username="root"
              password="admin"
              driverClassName="com.mysql.jdbc.Driver"
              url="jdbc:mysql://localhost:3306/library" />
</Context>

error.jsp文件

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Upss</title>
</head>
<body>
<h1>Something is wrong</h1>
<a href="index.jsp">Try again</a>
</body>
</html>

的index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>Library Viewer</title>
</head>
<body>
<h1>Biblioteka viewer</h1>
<form action="BookServlet" method="post">
  <input placeHolder="ISBN" type="text" name="isbn">
  <br>
  <input placeHolder="Tytuł" type="text" name="title">
  <br>
  <input placeHolder="Opis" type="text" name="description">
  <br>
  Szukaj: <input type="radio" name="option" value="search"> Dodaj: <input type="radio" name="option" value="add">
  Modyfikuj: <input type="radio" name="option" value="update"> Usuń: <input type="radio" name="option" value="delete">
  <br>
  <input type="submit" value="Wyślij">
</form>

</body>
</html>

result.jsp中

<%@page import="pl.javastart.model.Book"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<% Book book = (Book)request.getAttribute("book"); %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
</head>
<body>
<h1>Wynik zapytania <%= request.getAttribute("option") %></h1>
<p>W wyniku Twojego zapytania otrzymano następujacy wynik:</p>
<p>Title: <%= book.getTitle() %><br>
    ISBN: <%= book.getIsbn() %><br>
    Descrition: <%= book.getDescription() %></p>
</body>
</html>

Book.java

package pl.javastart.model;

public class Book {
    private String isbn;
    private String title;
    private String description;
    public String getIsbn() {
        return isbn;
    }
    public void setIsbn(String isbn) {
        this.isbn = isbn;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }

    public Book(){}
    public Book(String isbn, String title, String desc){
        this.isbn = isbn;
        this.title = title;
        description = desc;
    }
}

BookServlet.java

package pl.javastart.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import pl.javastart.dao.BookDAO;
import pl.javastart.model.Book;

@WebServlet("/BookServlet")
public class BookServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String isbn = request.getParameter("isbn");
        String title = request.getParameter("title");
        String description = request.getParameter("description");
        String option = request.getParameter("option");
        BookDAO dao = new BookDAO();
        Book book = null;
        String operation = null;
        boolean result = false;
        if("search".equals(option)) {
            book = dao.read(isbn);
            result = book!=null? true:false;
            operation = "search";
        } else if("add".equals(option)) {
            book = new Book(isbn, title, description);
            result = dao.create(book);
            operation = "add";
        } else if("update".equals(option)) {
            book = new Book(isbn, title, description);
            result = dao.update(book);
            operation = "update";
        } else if("delete".equals(option)) {
            book = new Book(isbn, title, description);
            result = dao.delete(book);
            operation = "delete";
        }
        if(book != null && result) {
            request.setAttribute("option", operation);
            request.setAttribute("book", book);
            request.getRequestDispatcher("result.jsp").forward(request, response);
        } else {
            request.getRequestDispatcher("error.jsp").forward(request, response);
        }
    }

}

BookDAO.java

package pl.javastart.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import pl.javastart.model.Book;
import pl.javastart.util.ConnectionProvider;

public class BookDAO {

    private final static String CREATE = "INSERT INTO book(isbn, title, description) VALUES(?, ?, ?);";
    private final static String READ = "SELECT isbn, title, description FROM book WHERE isbn = ?;";
    private final static String UPDATE = "UPDATE book SET isbn=?, title=?, description=? WHERE isbn = ?;";
    private final static String DELETE = "DELETE FROM book WHERE isbn=?;";

    public boolean create(Book book) {
        Connection conn = null;
        PreparedStatement prepStmt = null;
        boolean result = false;
        try {
            conn = ConnectionProvider.getConnection();
            prepStmt = conn.prepareStatement(CREATE);
            prepStmt.setString(1, book.getIsbn());
            prepStmt.setString(2, book.getTitle());
            prepStmt.setString(3, book.getDescription());
            int rowsAffected = prepStmt.executeUpdate();
            if (rowsAffected > 0) {
                result = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            releaseResources(prepStmt, null, conn);
        }
        return result;
    }

    public Book read(String isbn) {
        Connection conn = null;
        PreparedStatement prepStmt = null;
        ResultSet resultSet = null;
        Book resultBook = null;
        try {
            conn = ConnectionProvider.getConnection();
            prepStmt = conn.prepareStatement(READ);
            prepStmt.setString(1, isbn);
            resultSet = prepStmt.executeQuery();
            if(resultSet.next()) {
                resultBook = new Book();
                resultBook.setIsbn(resultSet.getString("isbn"));
                resultBook.setTitle(resultSet.getString("title"));
                resultBook.setDescription(resultSet.getString("description"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            releaseResources(prepStmt, resultSet, conn);
        }
        return resultBook;
    }

    public boolean update(Book book) {
        Connection conn = null;
        PreparedStatement prepStmt = null;
        boolean result = false;
        try {
            conn = ConnectionProvider.getConnection();
            prepStmt = conn.prepareStatement(UPDATE);
            prepStmt.setString(1, book.getIsbn());
            prepStmt.setString(2, book.getTitle());
            prepStmt.setString(3, book.getDescription());
            prepStmt.setString(4, book.getIsbn());
            int rowsAffected = prepStmt.executeUpdate();
            if (rowsAffected > 0) {
                result = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            releaseResources(prepStmt, null, conn);
        }
        return result;
    }

    public boolean delete(Book book) {
        Connection conn = null;
        PreparedStatement prepStmt = null;
        boolean result = false;
        try {
            conn = ConnectionProvider.getConnection();
            prepStmt = conn.prepareStatement(DELETE);
            prepStmt.setString(1, book.getIsbn());
            int rowsAffected = prepStmt.executeUpdate();
            if (rowsAffected > 0) {
                result = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            releaseResources(prepStmt, null, conn);
        }
        return result;
    }

    private void releaseResources(PreparedStatement prepStmt, ResultSet res,
                                  Connection conn) {
        try {
            if (prepStmt != null && !prepStmt.isClosed()) {
                prepStmt.close();
            }
            if (res != null && !res.isClosed()) {
                res.close();
            }
            if (conn != null && !conn.isClosed()) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}

ConnectionProvider.java

package pl.javastart.util;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class ConnectionProvider {
    private static DataSource dataSource;

    public static Connection getConnection() throws SQLException {
        return getDSInstance().getConnection();
    }

    private static DataSource getDSInstance() {
        if(dataSource == null) {
            try {
                Context initContext = new InitialContext();
                Context envContext = (Context) initContext.lookup("java:comp/env");
                dataSource = (DataSource) envContext.lookup("jdbc/library");
            } catch (NamingException e) {
                e.printStackTrace();
            }
        }
        return dataSource;
    }
}

Dao.iml

<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
  <component name="FacetManager">
    <facet type="web" name="Web">
      <configuration>
        <descriptors>
          <deploymentDescriptor name="web.xml" url="file://$MODULE_DIR$/web/WEB-INF/web.xml" />
        </descriptors>
        <webroots>
          <root url="file://$MODULE_DIR$/web" relative="/" />
        </webroots>
      </configuration>
    </facet>
  </component>
  <component name="NewModuleRootManager" inherit-compiler-output="true">
    <exclude-output />
    <content url="file://$MODULE_DIR$">
      <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
    </content>
    <orderEntry type="inheritedJdk" />
    <orderEntry type="sourceFolder" forTests="false" />
    <orderEntry type="library" scope="PROVIDED" name="Tomcat 9.0.0.M9" level="application_server_libraries" />
    <orderEntry type="library" name="mysql-connector-java-5.1.39-bin" level="project" />
  </component>
</module>

这是一个包含项目结构的屏幕:enter image description here

和控制台:enter image description here

2 个答案:

答案 0 :(得分:1)

在context.xml中

<Resource name="jdbc/library"
          global="jbc/library"
          ...

看起来global键的值可能缺少一个字母。

另一方面,getConnection()我在线查找的所有示例都包含网址的字符串参数,例如: this Mkyong article,但在代码中的位置看起来不像那样。 ConnectionProvider.getConnection()在通过它进行调试时是否实际返回了任何内容?

答案 1 :(得分:1)

问题解决了。我不得不添加META-INF目录并移动context.xml 屏幕附着enter image description here