【发布时间】:2013-01-18 12:32:24
【问题描述】:
我有一个来自 javascript 文件的 ajax 调用,我想将要删除的用户的 ID 作为参数传递:
function eliminaUtente(id,nome){
if (confirm("Sei sicuro di voler eliminare l'utente "
+ nome
+ "?")) {
var xmlHttp2 = new XMLHttpRequest();
xmlHttp2.open("POST", "EliminaUtente", true);
xmlHttp2.setRequestHeader("Content-type",
"application/x-www-form-urlencoded");
var params2 = "id=" + id;
xmlHttp2.send(params2);
xmlHttp2.onreadystatechange = function() {
if (xmlHttp2.readyState == 4)
{
alert(xmlHttp2.status); <-----------this prints always 0!
if (xmlHttp2.status == 200) //
{
alert("utente eliminato!");
} else {
alert("An error occurred while communicating with server.");
}
}
};
} }
在名为 EliminaUtente 的对应 Servlet 中,我有以下代码:
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String id = request.getParameter("id");
System.out.println(id);
String query = "delete from utente where idutente=" + id;
System.out.println(query);
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager
.getConnection("jdbc:mysql://localhost/Spinning?user=root");
PreparedStatement prest = con.prepareStatement(query);
prest.executeUpdate();
response.setContentType("text/plain");
PrintWriter ajaxWriter = response.getWriter();
ajaxWriter.print("ok");
ajaxWriter.flush();
ajaxWriter.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
response.setContentType("text/plain");
PrintWriter ajaxWriter = response.getWriter();
ajaxWriter.print("ko");
ajaxWriter.flush();
ajaxWriter.close();
}
}
}
我不明白问题出在哪里……你能帮帮我吗? ;)
【问题讨论】:
-
Code 0 表示存在连接问题。
-
是的,但我不明白在哪里!代码似乎正确...
-
阅读准备好的语句。您真的不希望有人使用
id=5 or 1=1发布请求并删除您的所有用户。 -
@JBNizet 你是什么意思?
-
任何人都可以使用
id=5 or 1=1作为查询字符串向您的webapp发送请求,并且由于您盲目地将id连接到您的SQL查询,因此将执行以下查询:delete from utente where idutente=5 or 1=1,这将删除应用程序中的所有用户。这就是为什么应始终使用准备好的语句而不是字符串连接:download.oracle.com/javase/tutorial/jdbc/basics/prepared.html。我描述的是SQL注入攻击:en.wikipedia.org/wiki/SQL_injection
标签: java javascript ajax servlets xmlhttprequest