我是第一次使用 JSP
和 Ajax
。我正在尝试从数据库获取一列数据,并使用 Ajax 调用将其填充到 JSP 页面的下拉列表中。我不想刷新页面,所以这就是原因,我正在进行 Ajax 调用。
这是我的 jsfiddle它有“进程”按钮,一旦我单击“进程”按钮,它现在就会显示一个空的下拉列表。这是我的另一个 test.jsp
页面。
我有一个表作为 account
,我需要从 jsp 中进行此选择查询 -
SELECT USERS FROM ACCOUNT;
一旦我单击“进程”按钮,我就需要使用 Ajax 在我的 POSTGRESQL 数据库上执行上述 SQL 查询。无论我从数据库中返回什么用户,我都需要在下拉列表中填充这些 USERS
,如上面的 jsfiddle 所示。
下面是我使用 Ajax 从 JSP 页面调用的 servlet 代码。
@WebServlet("/someservlet/*")
public class SomeServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) {
try {
System.out.println("Hello Test");
// Step 1. Load the JDBC driver
Class.forName("org.postgresql.Driver");
// Step 2. Create a Connection object
Connection con = DriverManager.getConnection(
"jdbc:postgresql://localhost/test","root", "root!");
Statement s = con.createStatement();
String sql ="SELECT USERS FROM ACCOUNT";
ResultSet rs = s.executeQuery(sql);
List<String> list = new ArrayList<String>();
while (rs.next()) {
list.add(rs.getString("email"));
}
String json = new Gson().toJson(list);
response.getWriter().write(json);
rs.close();
s.close();
con.close();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (SQLException e2) {
e2.printStackTrace();
} catch (Exception e3) {
e3.printStackTrace();
}
}
}
下面是我从上面的 jsp 页面进行的 jquery ajax 调用,如 jsfiddle 中所示,我在单击 Process
按钮时调用上面的 servlet -
<script type="text/javascript">
$(document).ready(function() {
$('.btn-primary').click(function() {
alert("Hello");
$.get('someservlet', function(responseJson) {
alert(responseJson);
var $ul = $('<ul>').appendTo($('#somediv'));
$.each(responseJson, function(index, item) {
$('<li>').text(item).appendTo($ul);
});
});
});
});
</script>
问题陈述:-
但不知怎的,它根本不起作用,这意味着我的 servlet 根本没有使用 Ajax 从我的 JSP 页面调用。我的 System.out 也没有从 servlet 打印在控制台上。
另外,我还有一个 servlet。这是我创建的第二个 servlet。可能是这个原因?
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
</web-app>
最佳答案
问题是这个类不是 Servlet
。它就像一个普通的 Java 类。
它应该扩展 HttpServlet
public class SomeServlet extends HttpServlet
此注释所在的类 @WebServlet声明必须扩展 HttpServlet .
Always try to use @Override annotation for overridden method to catch such type of errors at compile type itself.
关于java - 在JSP中使用jquery ajax没有调用Servlet?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24094443/