1
我想在Java
上使用Ajax
製作一個簡單的web應用程序。我有一個表的本地數據庫 - 兩列:ID
和Surname
。 。不工作的servlet從數據庫中提取值
我的應用程序應該顯示用戶正確surname
(例如,他在現場id = 1
和servlet應該從數據庫返回的姓氏寫
這是我的servlet:
package db.connection;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* Servlet implementation class ConnectionServlet
*/
@WebServlet("/ConnectionServlet")
public class ConnectionServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String key = req.getParameter("key");
if (key != null) {
String surname = "";
ResultSet result = null;
Connection con = null;
try{
con = DatabaseConnector.getConnection();
Statement select = con.createStatement();
result = select
.executeQuery("SELECT surname from person where ID = '"
+ key + "';");
//surname=result.getString(0);
while (result.next()) {
surname = result.getString("surname");
// System.out.println(surname);
}
res.setContentType("text/xml");
res.setHeader("Cache-Control", "no-cache");
// write out the response string
res.getWriter().write(surname);
}
catch (SQLException e)
{
{
System.out.println(e.getMessage());
} }
finally
{
if (con != null)
{
try
{
con.close();
} catch (SQLException e) {
}
}
}
}
}
}
Ajax.js
var req;
function getSurDB(){
var key = document.getElementById("key");
var keypressed = document.getElementById("keypressed");
keypressed.value = key.value;
var url = "/DBcon/Ajax?key="+ escape(key.value);
if (window.XMLHttpRequest){
req = new XMLHttpRequest();
}
else if (window.ActiveXObject){
req = new ActiveXObject("Microsoft.XMLHTTP");
}
req.open("Get",url,true);
req.onreadystatechange = callback;
req.send(null);
}
function callback(){
if (req.readyState==4){
if (req.status == 200){
var surname = document.getElementById('surname');
surname.value = req.responseText;
}
}
clear();
}
function clear(){
var key = document.getElementById("key");
key.value="";
}
function focusIn(){
document.getElementById("key").focus();
}
你的意圖不錯,但是你面臨什麼問題? –
考慮使用預處理語句,以便處理SQL注入。而不是executeQuery(「SELECT姓氏來自ID ='」+ key +「';」的人)更多信息:https://www.owasp.org/index.php/Preventing_SQL_Injection_in_Java – Mike
用戶在網站上編寫身份證時看不到任何東西。 它是我的第一個作業。我知道SQL注入,但首先我想看到這個應用程序的工作,接下來我會考慮安全。 – KrisPL