投稿する例では、サーブレットをプログラムする必要があります。そのサーブレットでは、ビジネス ロジック呼び出し (この場合はデータベース クエリ) を行います。データを取得した後、それを JSP ページに渡す必要があります。 . サーブレットでは main メソッドは必要ありませんが、サーブレット コンテナー (Tomcat など) にデプロイする必要があります。
コードは次のとおりです。
public class UserListServlet extends 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を使用すると、この例を改善できます。