如何将 mysql-connector-driver 与 jsp 一起使用

How to use mysql-connector-driver with jsp

我需要使用 JSP 创建登录,因此,我需要使用 mysql-connector-java

我将文件 jar: mysql-connector-java-5.1.38-bin.jar 插入 WEB-INF/lib

我将此代码用于 jsp 文件:

<%@ 
        page import="java.sql.*"
    %>

<%
    String DRIVER = "com.mysql.jdbc.Driver";
    String URL_mioDB = "jdbc:mysql://localhost:3306/ditta";

    try
    {
       Class.forName(DRIVER);
    } 
    catch (ClassNotFoundException e) 
    {
       System.err.println("Driver not found" + e);
    } 

    Connection connessione = null;
    try
    {
       // apro la connesione verso il database.
       connessione = DriverManager.getConnection(URL_mioDB,"root","");
    } 
    catch (Exception e)
    {
       System.err.println("Error during connection with db : " + e);
    } 

    String mail="",pass="",send="",query="";

    try
    {
        mail=request.getParameter("email");
        pass=request.getParameter("password");
        send=request.getParameter("send");

        out.println("<FORM name='F1' method='post' action='login.jsp'>");
            out.println("Email: <INPUT type='text' name='email' value='' placeholder='mariorossi@gmail.com'><BR><BR>");
            out.println("Password: <INPUT type='password' name='password' value=''><BR><BR>");
            out.println("<INPUT type='submit' name='send' value='Invia'>&nbsp;&nbsp;&nbsp;&nbsp;<INPUT type='reset' name='reset' value='Reset'>");
        out.println("</FORM>");
    }
    catch (Exception e)
    {
       System.err.println(e);  
    } 

    if(send!=null && mail!="" && pass!="")
    {
        query="SELECT * FROM dipendenti WHERE email="+ mail + " AND password=" + pass + "";

        Statement statement = connessione.createStatement();
        ResultSet resultSet = statement.executeQuery(query);
        ResultSetMetaData rsmd = resultSet.getMetaData();

        for(int i=0;i<=rsmd.getColumnCount();i++)
        {
            out.println(resultSet.getString(i));
            }
    }

%>

在那之后,当我点击发送按钮时,页面给我这个错误:

errors image

在这里猜测一下......

我想这可能与您如何将参数值传递到查询有关。因此,如果邮件是 "a@a.com",密码是 "a",那么您的查询最终是:

SELECT * FROM dipendenti WHERE email=a@a.com AND password=a

这不是正确的 SQL。您缺少 quotes/apostrophes。我会尝试这样查询:

SELECT * FROM dipendenti WHERE email='a@a.com' AND password='a'

这需要对您的定义方式进行简单更改

query=...

同时,我知道这不是你在这里问的,但我强烈建议你应该阅读 SQL Injection on Wikipedia 。你在这里做的不是接受用户输入到你的后端程序并最终进入数据库的正确方法。

对于这个非常具体的用例 JDBC(和数据库)有一个准备语句的概念: http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html

所以你会从类似的东西开始:

    // not tested
    query="SELECT * FROM dipendenti WHERE email=? AND password=?";
    PreparedStatement statement = connessione.prepareStatement(query);

    statement.setString(1, mail);
    statement.setString(2, pass);

    ResultSet resultSet = statement.executeQuery();