[英]Why there is Postgres exception?
下午好。 我嘗試從Eclipse的Java代碼連接到數據庫。 我需要發出請求,並檢查在表單中鍵入的用戶名和密碼是否彼此匹配。 用戶名及其密碼的列表位於名為stud_test的數據庫中。 我需要運行gradle和tomcat以便檢查servlet是否正常工作。 當我這樣做並打開所需的頁面時,我看到了PSQLExceptions。 我的代碼示例如下。 我不明白是什么問題。
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException {
Connection con;
ResultSet rs;
String URL = "jdbc:postgresql://localhost:5432/stud_test";
String username = request.getParameter("useruser");
String passwrd = request.getParameter("pass");
response.setContentType("text/html");
try {
con = DriverManager.getConnection(URL, "postgres", "postgres");
Statement st = con.createStatement();
st.executeQuery ("SELECT password FROM stud WHERE user = " + username);
rs = st.getResultSet();
if (passwrd.equals(rs)){
request.getServletContext().getRequestDispatcher(
"/jsp/hello.jsp").forward(request, response);
}
else {
request.getServletContext().getRequestDispatcher("/jsp/fail.jsp").forward(request, response);
}
rs.close ();
st.close ();
}
catch(Exception e) {
System.out.println("Exception is :" + e);
}
}
除了Sergiu已經提到的內容外,以下行不太可能做您想要的事情:
st.executeQuery ("SELECT password FROM stud WHERE user = " + username);
例如,如果用戶名是“ carl”,則將以下語句發送到數據庫:
SELECT password FROM stud WHERE user = carl
如果沒有名為“ carl”的列,則會導致語法錯誤。 解決此問題的“顯而易見”(和錯誤方法!)將使用
st.executeQuery ("SELECT password FROM stud WHERE user = '" + username + "'");
這可能會(首先)起作用,但使您容易受到SQL注入的攻擊。 請求信息的正確方法是使用准備好的語句和參數:
final PreparedStatement stm = connection.prepareStatement(
"SELECT password FROM stud WHERE user = ?");
try {
// For each "hole" ("?" symbol) in the SQL statement, you have to provide a
// value before the query can be executed. The holes are numbered from left to
// right, starting with the left-most one being 1. There are a lot of "setXxx"
// methods in the prepared statement interface, and which one you need to use
// depends on the type of the actual parameter value. In this case, we assign a
// string parameter:
stm.setString(1, username);
final ResultSet rs = stm.executeQuery();
try {
if (rs.next()) {
if (password.equals(rs.getString(1))) {
// Yay. Passwords match. User may log in
}
}
} finally {
rs.close();
}
} finally {
stm.close();
}
是的,通過Java中的JDBC與數據庫對話需要大量樣板代碼。 不,“顯而易見的”解決方案是錯誤的! 錯誤! 錯誤!
我想你應該有
if (passwrd.equals(rs.getString(1))){ ... }
假設用戶字段是數據庫中的varchar。
您不能將字符串(passwrd)與ResultSet實例(rs)匹配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.