I followed a tutorial online and there were some mistakes here and there but I understood the ideas behind it and the mindset. I have a school project on developing a Web App and I decided to do it in Java EE (since I was comfortable with Java).
My source code consists of 5 packages (Beans, Connection, Filter, Servlets and Utilities).
The problem consists of the JDBC Filter, as told in the title. It checks that everywhere on the website, I'm still connected to the MySQL Database. However, whenever it goes on anything of a localhost:8080/*, an SQL Exception is enabled, complaining about the Driver. Except this error doesn't arrive when opening files directly in the path, instead of using URL Patterns.
So I decided to do some investigating. Checked the console and climbed up the errors. It complained about the ConnectionUtils
class, specifically the getMySQLConnection
method, which comes from the MySQLConnUtils
class.
The problem is that when I try the method itself in the main
method, it works !
package Connection;
import java.sql.Connection;
import java.sql.SQLException;
public class ConnectionUtils {
public static Connection getMyConnection() throws SQLException, ClassNotFoundException{
return MySQLConnUtils.getMySQLConnection();
}
public static void closeQuietly(Connection conn)
{
try{
conn.close();
}catch(Exception e){
}
}
public static void rollbackQuietly(Connection conn){
try{
conn.rollback();
}catch(Exception e){
}
}
public static void main(String[] args) throws SQLException, ClassNotFoundException {
System.out.println("Get connection...");
Connection conn = ConnectionUtils.getMyConnection();
System.out.println("Get connection " + conn);
System.out.println("Done!");
}
}
package Connection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MySQLConnUtils {
public static Connection getMySQLConnection() throws SQLException{
String userName = "username";
String password="pwd";
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("CLASS NOT FOUND");
}
String connectionURL = "jdbc:mysql://localhost:3306/flytogo";
Connection conn = DriverManager.getConnection(connectionURL,userName,password);
return conn;
}
}
Here's the filter proving that the url-pattern it applies to is "/*" :
package Filter;
import java.io.IOException;
import java.sql.Connection;
import java.util.Collection;
import java.util.Map;
import Connection.ConnectionUtils;
import Utils.MyUtils;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
@WebFilter(filterName = "jdbcFilter", urlPatterns = { "/*" })
public class JDBCFilter implements Filter {
public JDBCFilter() {
}
@Override
public void init(FilterConfig fConfig) throws ServletException {
}
@Override
public void destroy() {
}
// Check the target of the request is a servlet?
private boolean needJDBC(HttpServletRequest request) {
System.out.println("JDBC Filter");
//
// Servlet Url-pattern: /spath/*
//
// => /spath
String servletPath = request.getServletPath();
// => /abc/mnp
String pathInfo = request.getPathInfo();
String urlPattern = servletPath;
if (pathInfo != null) {
// => /spath/*
urlPattern = servletPath + "/*";
}
// Key: servletName.
// Value: ServletRegistration
Map<String, ? extends ServletRegistration> servletRegistrations = request.getServletContext()
.getServletRegistrations();
// Collection of all servlet in your Webapp.
Collection<? extends ServletRegistration> values = servletRegistrations.values();
for (ServletRegistration sr : values) {
Collection<String> mappings = sr.getMappings();
if (mappings.contains(urlPattern)) {
return true;
}
}
return false;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
// Only open connections for the special requests.
// (For example, the path to the servlet, JSP, ..)
//
// Avoid open connection for commons request.
// (For example: image, css, javascript,... )
//
if (this.needJDBC(req)) {
System.out.println("Open Connection for: " + req.getServletPath());
Connection conn = null;
try {
// Create a Connection.
conn = ConnectionUtils.getMyConnection();
// Set outo commit to false.
conn.setAutoCommit(false);
// Store Connection object in attribute of request.
MyUtils.storeConnection(request, conn);
// Allow request to go forward
// (Go to the next filter or target)
chain.doFilter(request, response);
// Invoke the commit() method to complete the transaction with the DB.
conn.commit();
} catch (Exception e) {
e.printStackTrace();
ConnectionUtils.rollbackQuietly(conn);
throw new ServletException();
} finally {
ConnectionUtils.closeQuietly(conn);
}
}
// With commons requests (images, css, html, ..)
// No need to open the connection.
else {
// Allow request to go forward
// (Go to the next filter or target)
chain.doFilter(request, response);
}
}
}
Anyways, thanks in advance to anyone who would know what could be the source of mistakes or error.