Baserat på Luiggis input om att inte skapa datakällan manuellt i en klass och rekommendation att använda JNDI-databaspooling, kunde jag få lösningen nedan att fungera. Min anpassning är starkt baserad på denna länk:http://www.codejava.net/servers/tomcat/ configuring-jndi-datasource-for-database-connection-pooling-in-tomcat
Bitar:Tomcat 8.0, postgresql-jdbc drivrutin, DBEngine bean, servlet
dbEngine-bönan består av tre klasser:DBEngine.java, Pool.java och SQLPS.java (ett SQL-satsbibliotek) som alla lindas in i en jar-fil och importeras till servleten och markeras som ett exportberoende för klassvägar.
Servletten som anropar bönan ser ut så här:
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 ut så här:
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;
}
}
och Pool.java ser ut så här:
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;
}
}
}
Jag var tvungen att lägga till dessa rader i $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*"
/>
och dessa rader till $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>
och postgresql-jdbc-burken gick in i $CATALINA_HOME/lib