Baseret på Luiggis input vedrørende ikke manuelt at oprette datakilden i en klasse og anbefaling om at bruge JNDI database pooling, var jeg i stand til at få nedenstående løsning til at fungere. Min tilpasning er stærkt baseret på dette link:http://www.codejava.net/servers/tomcat/ configuring-jndi-datasource-for-database-connection-pooling-in-tomcat
Stykker:Tomcat 8.0, postgresql-jdbc driver, DBEngine bean, servlet
dbEngine-bønnen består af tre klasser:DBEngine.java, Pool.java og SQLPS.java (et SQL-sætningsbibliotek), der alle er pakket ind i én jar-fil og importeret til servlet'en og markeret som en klassesti-eksportafhængighed.
Servletten, der kalder bønnen, ser sådan ud:
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);
}
}
dbEngine.java ser sådan ud:
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;
}
}
og Pool.java ser sådan ud:
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;
}
}
}
Jeg var nødt til at tilføje disse linjer til $CATALINA_HOME/conf/context.xml:
<Resource
name="jdbc/postgres4"
auth="Container"
type="javax.sql.DataSource"
maxActive="8"
maxIdle="8"
driverClassName="org.postgresql.Driver"
url="*URL*"
username="*UserName*"
password="*Password*"
/>
og disse linjer til $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>
og postgresql-jdbc-krukken gik ind i $CATALINA_HOME/lib