Basierend auf Luiggis Input, die Datenquelle nicht manuell in einer Klasse zu erstellen, und der Empfehlung, JNDI-Datenbankpooling zu verwenden, konnte ich die folgende Lösung zum Laufen bringen. Meine Anpassung basiert stark auf diesem Link:http://www.codejava.net/servers/tomcat/ konfigurieren-jndi-datasource-for-database-connection-pooling-in-tomcat
Teile:Tomcat 8.0, postgresql-jdbc-Treiber, DBEngine-Bean, Servlet
Die dbEngine-Bean besteht aus drei Klassen:DBEngine.java, Pool.java und SQLPS.java (eine SQL-Anweisungsbibliothek), die alle in eine JAR-Datei verpackt und in das Servlet importiert und als Klassenpfad-Exportabhängigkeit markiert sind.
Das Servlet, das die Bean aufruft, sieht so aus:
package com.engine.main;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentMap;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
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 sslog4java.LogLevel;
import sslog4java.Logger;
import com.google.gson.Gson;
import com.DBbean.DBEngine;
@WebServlet("/PrimaryEngine")
public class PrimaryEngine extends HttpServlet {
private static final long serialVersionUID = 1L;
private DBEngine db = null;
private static String filePath = "";
private static String fileName = "";
Logger fLogger = null;
public void init(ServletConfig config) throws ServletException{
super.init(config);
ServletContext scxt = config.getServletContext();
filePath = scxt.getRealPath("/WEB-INF") + "\\logs\\";
fileName = "loggerFileName";
fLogger = new Logger(filePath, fileName, LogLevel.DEBUG);
try {
// passed the servlet context into the DBengine for the pool to use
db = new DBEngine(new InitialContext(), fLogger);
} catch (SQLException | NamingException e) {
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
if(request.getParameterMap().containsKey("param") && request.getParameter("param").equals("paramValue")){
test = db.DBdebug();
out.println(test);
return;
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
Die dbEngine.java sieht so aus:
package com.DBbean;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import javax.naming.Context;
import sslog4java.Logger;
import com.google.common.collect.MapMaker;
public class DBEngine {
private Pool pool = null;
private Connection con = null;
private Logger fLogger;
public DBEngine(Context initCtx, Logger logr) throws SQLException{
this.fLogger = logr;
// passed the servlet context into the Pool.java
this.pool = new Pool(initCtx);
this.con = pool.getConnection();
}
public String DBdebug(){
Connection conn = pool.getConnection();
try {
String ps = SQLPS.debugSQL;
PreparedStatement ps2 = conn.prepareStatement(ps);
ResultSet rs = ps2.executeQuery();
if(rs.next()){
return "Success";
} else return "Fail";
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
und die Pool.java sieht so aus:
package com.DBbean;
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class Pool {
Context ctx;
public Pool(Context context){
ctx = context;
}
public Connection getConnection() {
try {
DataSource ds = (DataSource) ctx.lookup("java:/comp/env/jdbc/postgres4" );
return ds.getConnection();
} catch (SQLException | NamingException sne) {
sne.printStackTrace();
return null;
}
}
}
Ich musste diese Zeilen zu $CATALINA_HOME/conf/context.xml hinzufügen:
<Resource
name="jdbc/postgres4"
auth="Container"
type="javax.sql.DataSource"
maxActive="8"
maxIdle="8"
driverClassName="org.postgresql.Driver"
url="*URL*"
username="*UserName*"
password="*Password*"
/>
und diese Zeilen zu $CATALINA_HOME/conf/web.xml:
<resource-ref>
<description>postgreSQL Datasource</description>
<res-ref-name>jdbc/postgres4</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
und das postgresql-jdbc-jar ging in $CATALINA_HOME/lib