Berdasarkan masukan Luiggi mengenai tidak secara manual membuat sumber data di kelas dan rekomendasi untuk menggunakan kumpulan basis data JNDI, saya bisa mendapatkan solusi di bawah ini untuk bekerja. Adaptasi saya sangat didasarkan pada tautan ini:http://www.codejava.net/servers/tomcat/ configuring-jndi-datasource-for-database-connection-pooling-in-Tomcat
Potongan:Tomcat 8.0, driver postgresql-jdbc, kacang DBEngine, servlet
Kacang dbEngine terdiri dari tiga kelas:DBEngine.java, Pool.java, dan SQLPS.java (perpustakaan pernyataan SQL) yang semuanya dibungkus menjadi satu file jar dan diimpor ke servlet dan ditandai sebagai dependensi ekspor classpath.
Servlet yang memanggil kacang terlihat seperti:
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 terlihat seperti:
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;
}
}
dan Pool.java terlihat seperti:
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;
}
}
}
Saya harus menambahkan baris ini ke $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*"
/>
dan baris ini ke $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>
dan toples postgresql-jdbc masuk ke $CATALINA_HOME/lib