今天要新增的功能是從網頁端查詢table的資料!
首先我們要新創一個class,叫做queryData,再去web.xml配置servlet,大概長這樣
<servlet>
<servlet-name>queryData</servlet-name>
<servlet-class>Package1.queryData</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>queryData</servlet-name>
<url-pattern>/queryTable</url-pattern>
</servlet-mapping>
在queryData這個class裡面我們沒有要輸入資料,所以使用Get方法,一定要先設定成UTF-8再宣告PrintWriter,不然中文會全部變成"??",PreparedStatement用的是之前介紹過的select查詢
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
queryTable(out);
}
public void queryTable(PrintWriter out) {
String selectSQL = "SELECT * FROM student_information ";
try ( Connection connection = DriverManager.getConnection(JDBC_url, JDBC_user, JDBC_password);
PreparedStatement preparedStatement = connection.prepareStatement(selectSQL)) {
ResultSet resultSet = preparedStatement.executeQuery();
out.println("<html><body>");
out.println("<h1>Student Information</h1>");
out.println("<table border='1'>");
out.println("<tr><th>學號</th><th>姓名</th><th>性別</th><th>年齡</th></tr>");
while (resultSet.next()) {
int number = resultSet.getInt("number");
String name = resultSet.getString("name");
String gender = resultSet.getString("gender");
int age = resultSet.getInt("age");
out.printf("<tr><td>%d</td><td>%s</td><td>%s</td><td>%d</td></tr>", number, name, gender, age);
}
out.println("</table>");
out.println("<button onclick=\"window.location.href='http://localhost:8080';\">返回首頁</button>");
out.println("</body></html>");
} catch (SQLException e) {
e.printStackTrace();
}
}
下面的while迴圈是逐一瀏覽資料並以html的語法輸出成表格,最後一段的button的作用是創建一個回到首頁的按鈕。
來看看實際畫面吧,輸入一筆神奇的資料
返回首頁後按下"查看資料表"按鈕
資料確實有進去,表格也成功出現了!