Tomcat MySQL连接数据源无法正常工作

时间:2015-08-19 12:57:00

标签: java tomcat jdbc

我在我的应用程序中编写了数据库连接的硬编码,现在我试图让它变得更好。问题是我似乎做了应该完成的所有事情,但它仍然失败了。

1-下载适合您平台的二进制发行版,解压缩JAR文件,然后将其复制到" $ CATALINA_HOME / lib" - 完成。

2-将MySQL数据库配置为JNDI资源。作为应用程序的上下文中的资源元素和应用程序中的资源引用" WEB-INF / web.xml"文件。

<Resource name="jdbc/storagerDB"

            auth="Container"

            type="javax.sql.DataSource"

            username="root"

            password="admin"

            driverClassName="com.mysql.jdbc.Driver"

            url="jdbc:mysql:/localhost:3306/storagerDB"

            maxActive="15"

            maxIdle="3"/>

 <resource-ref>
<description>MySQL Datasource example</description>
<res-ref-name>jdbc/storagerDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>

public class DataAccessObject {

private CustomLogger logger = new CustomLogger(DataAccessObject.class);

private Statement stmt;
private Connection conn;
private DataSource ds;
private Context ctxt;

/**
 * Queries that creates the db.
 */
private static final String[] DB_CREATION_QUERIES = new String[] {

        "CREATE DATABASE IF NOT EXISTS storagerDB;", "USE storagerDB;",

        "CREATE TABLE IF NOT EXISTS user(id int NOT NULL PRIMARY KEY AUTO_INCREMENT,"
                + "username varchar(25) NOT NULL, password varchar(250) NOT NULL,"
                + "salt varchar(250) NOT NULL, email varchar(35) NOT NULL);",

        "CREATE TABLE IF NOT EXISTS header(id int NOT NULL PRIMARY KEY AUTO_INCREMENT,"
                + "user_id int, Foreign Key (user_id) REFERENCES user(id)," + "server varchar(50) NOT NULL,"
                + "content_type varchar(50) NOT NULL," + "status_code int NOT NULL," + "url varchar(250) NOT NULL);"

};

/**
 * Constructor JDBC driver could be initialized and loaded in Tomcat/lib
 * @throws NamingException 
 */
public DataAccessObject() {
    try {
        ctxt = new InitialContext();
        ds = (DataSource)ctxt.lookup("java:comp/env/jdbc/storagerDB");
        conn = ds.getConnection();

        stmt = conn.createStatement();

        for (String query : DB_CREATION_QUERIES) {
            stmt.execute(query);
        }

    }   catch (SQLException | NamingException e) {
        logger.logExceptionMessage("DAO constructor SQL", e.getStackTrace());
    }

}

它失败了&#34; ds =(DataSource)ctxt.lookup(&#34; java:comp / env / jdbc / storagerDB&#34;)&#34;。

Exception in thread "main" javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
at javax.naming.spi.NamingManager.getInitialContext(Unknown Source)
at javax.naming.InitialContext.getDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.lookup(Unknown Source)
at com.wordpress.belichev.model.DataAccessObject.<init>(DataAccessObject.java:58)
at com.wordpress.belichev.model.DataAccessObject.main(DataAccessObject.java:279)

1 个答案:

答案 0 :(得分:1)

您获得此var mongo = require('mongodb'); var Grid = require('gridfs-stream'); // create or use an existing mongodb-native db instance var db = new mongo.Db('yourDatabaseName', new mongo.Server("127.0.0.1", 27017)); var gfs = Grid(db, mongo); // ... req.busboy.on('file', function(fieldname, file, filename, encoding, mimetype) { console.log('File [' + fieldname + ']: filename: ' + filename); var gfsstream = gfs.createWriteStream('/uploads'); file.pipe(gfsstream).on('finish', function() { console.log('File [' + fieldname + '] Finished'); }); }); 的原因是您将此应用程序作为独立应用程序运行。这将忽略您的web.xml文件,包含所有资源定义。您需要将其作为webapp运行,甚至让它有机会工作。

在下一行中获取NPE(正如您在评论中提到的)是由于您的应用在上下文查找后未找到数据源。这是一个不同的问题,可能也与您的web.xml使用有关。我建议看看这个post来看看要点。