我想在Ajax
上使用Java
创建一个简单的Web应用程序。我有一个包含一个表的本地数据库 - 两列:ID
和Surname
。
我的应用程序应该向用户显示正确的surname
(例如,他在网站id = 1
上写道,而servlet应该从db返回姓氏。
这是我的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();
}
答案 0 :(得分:0)
很难找到您的问题,因为我们不知道您的DatabaseConnector类是否正常工作。同样在评论中你说tomcat显示错误。您可以在IDE或tomcat日志文件中检查tomcat控制台并分析错误(可能是google)。
但我发现了一个问题。 您将响应的内容类型设置为" text / xml"但是你返回一个String。 尝试将其设置为纯文本:
res.setContentType("text/plain");
或将姓氏返回为xml。