```
WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
Connection conn;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ResultSet rs = null;
PreparedStatement stmt = null;
try {
Context context = new InitialContext();
DataSource ds =(DataSource)context
.lookup("java:/comp/env/jdbc/servdb");
conn = ds.getConnection();
String sql = "SELECT * FROM users";
stmt = conn.prepareStatement(sql);
rs = stmt.executeQuery();
List<LogBean> logs = new ArrayList<>();
LogBean log = null;
while (rs.next()) {
log= new LogBean();
log.setId(rs.getInt("Id"));
log.setEmail(rs.getString("Email"));
log.setPassword(rs.getString("Password"));
log.setUsername(rs.getString("Username"));
logs.add(log);
}
request.setAttribute("logs", logs);
request.getRequestDispatcher("/jsp/register.jsp").forward(request, response);
} catch (Exception e) {
throw new ServletException(e);
} finally {
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
import="java.util.*,com.lcpan.bean.LogBean"%>
<%!@SuppressWarnings("unchecked")%>
<table border="1">
<tr style="background-color: #a8fefa">
<th>
<th>姓名
<th>使用者名稱
<th>密碼
<th>郵件
<%
List<LogBean> logs = (ArrayList<LogBean>) request.getAttribute("logs");
for (LogBean log : logs) {
%>
<tr>
<td><%=log.getId()%>
<td><%=log.getUsername()%>
<td><%=log.getEmail()%>
<td><%=log.getPassword()%> <%
}
%>
共<%=logs.size()%>筆會員資料
package com.lcpan.bean;
public class LogBean implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String username;
private String password;
private String email;
// Getters and setters
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
@Override
public String toString() {
return "LogBean [id=" + id + ", username=" + username + ", password=" + password + ", email=" + email + "]";
}
}
一直跑404
因為不清楚你的程式架構,但你說出現的404,猜測是相對路徑的問題
request.getRequestDispatcher("/jsp/register.jsp")
改為
request.getRequestDispatcher("register.jsp")