源代码:
package com.atguigu.javaweb;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection; //大神解答!!!
public class LoginServlet3 extends HttpServlet {
/**
*
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
String username = req.getParameter("username");
String password = req.getParameter("password");
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
PrintWriter out = resp.getWriter();
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/atguigu?setUnicode=true&characterEncoding=utf8";//重点!!!
String user = "root";
String password2 = "";
connection = DriverManager.getConnection(url,user,password2);
String sql = "SELECT count(id) FROM tableData WHERE username = ? " + "AND password = ?";//tableData是表名!!!url中的atguigu是数据库名!!!!
statement = ((java.sql.Connection) connection).prepareStatement(sql);
statement.setString(1, username);
statement.setString(2, password);
resultSet = statement.executeQuery();
if(resultSet.next()) {
int count = resultSet.getInt(1);
if(count > 0) {
out.println("Hello: " + username);
}else{
out.println("Sorry: " + username);
}
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(resultSet != null) {
resultSet.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(statement != null) {
statement.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(connection != null) {
connection.close();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
这是经过改正后的代码: String url="jdbc:mysql://localhost:3306/atguigu?setUnicode=true&characterEncoding=utf8";//重点!!!
改正前代码如下:
String url="jdbc:mysql://IP:3306/atguigu?user=root&password=&useUnicode="true";
其中IP忘记设置,没有设置密码的代码也不该如此。故而存在问题。
2. 我的引入包也存在问题,并且在这之前存在一个强制转换。我的这段代码:
connection = DriverManager.getConnection(url,user,password2);
import java.sql.Connection; //大神解答!!!
改正前是connection = (Connection)DriverManager.getConnection(url,user,password2);
import com.sun.corba.se.pept.transport.Connection;
导致了相当严重的失误。完全无法连接到数据库。
3. 另外在连接到的相应数据库的表时,也存在一些库名及表名不对称的问题。
这些代码:
String sql = "SELECT count(id) FROM tableData WHERE username = ? " + "AND password = ?"; //tableData是表名!!!url中的atguigu是数据库名!!!!
改正前是这样的:
String sql = "SELECT count(id) FROM users WHERE username = ? " + "AND password = ?";
很显然,问题出在了sql语句中的FROM后面的users。这个是完全错误的!!!
***************在解决完以上的问题后,经过web.xml配置后就可以正常通过对比数据库表中的username和password与登录界面的输入数据是否一致进而做出相应的响应了。***************************BINGO!!!