对于您发布的示例,您需要做的是编写一个 servlet,在该 servlet 中您将进行业务逻辑调用(在本例中为数据库查询),在获取数据后,您必须将其传递给 JSP 页面. 使用 servlet 不需要 main 方法,但它们必须部署在 servlet 容器(如 Tomcat)中。
这是代码:
公共类 UserListServlet 扩展 HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//Accessing driver from JAR
Class.forName("com.mysql.jdbc.Driver");
//Creating a variable for the connection called "con"
//jdbc:mysql://host_name:port/dbname
//Driver name = com.mysql.jdbc.Driver
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/wae","root","");
PreparedStatement statement = con.prepareStatement("select name from user");
ResultSet result = statement.executeQuery();
//creates a list with the user names
List<String> userList = new ArrayList<String>();
while(result.next()) {
userList.add(result.getString(1));
}
//passing the data to the JSP
request.setAttribute("users", userList);
getServletContext().getRequestDispatcher("/user_list.jsp").forward(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
现在在 JSP 中你可以有这样的东西:
<%@ page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page import="java.util.List" %>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>User List</title>
</head>
<body>
<%
if (request.getAttribute("userList") != null) {
List<String> users = request.getAttribute("userList");
%>
<h1>Users: </h1>
<table>
<tr>
<td>Name<</td>
</tr>
<% for (String name : users) {%>
<tr>
<td><%= name%></td>
</tr>
<% }
}%>
</table>
</body>
</html>
您可以通过使用JSTL而不是 Scriptlet (<% ... %>) 来改进此示例。