JDBC筛选器阻止所有Servlet和URL模式,但不直接访问文件本身

时间:2019-07-04 12:03:42

标签: java jsp servlets jdbc filter

我在网上{@ {3}}进行了跟踪,到处都有一些错误,但是我了解其背后的想法和思维方式。我有一个关于开发Web App的学校项目,我决定用Java EE来做(因为我对Java很满意)。

我的源代码包含5个程序包(Bean,连接,过滤器,Servlet和实用程序)。

问题如标题中所述,由JDBC筛选器组成。它检查网站上的所有地方是否仍连接到MySQL数据库。但是,无论何时在localhost:8080 / *上进行任何处理,都会启用SQL异常,并抱怨tutorial。直接在路径中而不是使用URL模式打开文件时,不会出现此错误。

因此,我决定进行一些调查。检查控制台并爬上错误。它抱怨ConnectionUtils类,特别是getMySQLConnection类的MySQLConnUtils方法。

问题在于,当我在main方法中尝试方法本身时,它会Driver

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;
    }
}

以下是过滤器,证明其适用的网址格式为“ / *”:

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);
        }

    }

}

无论如何,在此先感谢那些知道错误或错误根源的人。

0 个答案:

没有答案