【发布时间】:2019-08-06 19:18:48
【问题描述】:
我正在尝试将 JEE 应用程序连接到 MySQL 数据库。关于这个主题有很多文档和类似的问题,但到目前为止我找到的解决方案都没有工作(尽管如此,我可能特别想念一个,所以请随意提出)。
服务器名称为db,数据库名称为joinmyparty
这是我要连接的 java 代码:
public class MySqlConnection {
private static Connection conn;
public static Connection getConn() {
try {
Context initContext = new InitialContext() ;
Context envContext = (Context)initContext.lookup("java:/comp/env") ;
DataSource ds = (DataSource) envContext.lookup("jdbc/joinmyparty") ;
conn = ds.getConnection();
} catch (NamingException e) {
System.out.println("Cannot get connection: " + e);
} catch (SQLException e) {
System.out.println("Cannot get connection: " + e);
}
return conn;
}
每次调用DAO时,我都会使用getConn()这个方法打开一个连接,然后在finally块中关闭它。
我把这个写到我的/tomcat/conf/context.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<WatchedResource>WEB-INF/tomcat-web.xml</WatchedResource>
<WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>
<Resource url="jdbc:mysql://db:3306/joinmyparty"
driverClassName="com.mysql.jdbc.Driver" password="mypassword"
username="myusername" maxWait="10000" maxIdle="30"
maxActive="100" type="javax.sql.DataSource" auth="Container"
name="jdbc/joinmyparty" validationQuery="select 1" testOnBorrow="true"/>
</Context>
我尝试将 mysql-connector .jar 放入 /tomcat/lib 或 /WEB-INF/lib 并放入构建路径。我还尝试了多个版本的连接器(但一次只能一个),尤其是获得与 MySQL 数据库相同级别的连接器。
当我调用需要连接数据库的 servlet 时,我有一个带有 POST() 方法的空白页和一个带有 GET() 方法的错误 5OO。 这是日志错误(我尽量翻译它,因为我不是英语本地人):
description : this server has encountered an internal error which prevents it from fulfilling your request
exception
java.lang.NullPointerException
com.picco.user.dao.UserDao.findByEmail(UserDao.java:40)
com.picco.user.servlet.Index.doGet(Index.java:56)
javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
这里是相关的代码部分(但正如我所说,所有使用 DAO 的代码都有同样的问题)。
try {
UserDao udao = new UserDao();
User u = udao.findByEmail(myCookieVal);
SongDao sdao = new SongDao();
ArrayList<Song> list = sdao.getAllSongs(u.getId());
Random rd = new Random();
int count = udao.count();
request.setAttribute("currentSong", list.get(rd.nextInt(list.size())));
request.setAttribute("songList", list);
request.setAttribute("partyCount", count);
this.getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
} catch(SQLException e) {
e.printStackTrace();
} finally {
HsqlConnection.closeInstance();
}
如果我没有描述足够的问题,请随时向我询问详细信息。
【问题讨论】:
-
您发布的代码中具体是哪一行抛出了 NPE?
-
第一个使用 UserDao()
标签: java mysql jakarta-ee