我不明白如何使用ResultSet
将值传递给servlet中获取的jsp并显示它们。我看到很多例子。我不理解foreach
循环。为什么有两个变量?没有人再使用jsp:useBean
吗?
如何传递和显示数据。我尝试使用bean类,但ResultSet
中的数据是一个表,我不知道如何设置和获取所有行的值。
请帮忙。
这是servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Connection connection = null;
Statement stmt = null;
try {
StringBuffer data = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(NewServlet.class.getName()).log(Level.SEVERE, null, ex);
}
connection = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=DesktopScreen","sa","sa123");
stmt = connection.createStatement();
String query = "select * from ClientLogin";
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String UniqueId,ClientId,RequestedDateTime,ConnectionStatus;
UniqueId = rs.getString("UniqueID");
ClientId = rs.getString("ClientId");
RequestedDateTime = rs.getString("RequestDateTime");
ConnectionStatus = rs.getString("ConnectionStatus");
BeanClass beanClass = new BeanClass();
beanClass.setUniqueId(UniqueId);
beanClass.setClientId(ClientId);
beanClass.setConnectionStatus(ConnectionStatus);
beanClass.setRequestDateTime(RequestedDateTime);
data = new StringBuffer();
data.append(UniqueId);
data.append(ClientId);
data.append(RequestedDateTime);
data.append(ConnectionStatus);
}
request.setAttribute("data", data);
request.getRequestDispatcher("Display.jsp").forward(request, response);
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
out.println("</center>");
out.print("</table>");
out.println("</body>");
out.println("</html>");
out.close();
try {
connection.close();
} catch (SQLException ex) {
Logger.getLogger(NewServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
答案 0 :(得分:0)
您可以将resultSet
放入List并将其传递给您的页面,并在JSP中提取此列表
Servlet: -
List <BeanClass> myList = new ArrayList<>();
while (rs.next()) {
String UniqueId,ClientId,RequestedDateTime,ConnectionStatus;
UniqueId = rs.getString("UniqueID");
ClientId = rs.getString("ClientId");
RequestedDateTime = rs.getString("RequestDateTime");
ConnectionStatus = rs.getString("ConnectionStatus");
BeanClass beanVar= new BeanClass();
beanVar.setUniqueId(UniqueId);
beanVar.setClientId(ClientId);
beanVar.setConnectionStatus(ConnectionStatus);
beanVar.setRequestDateTime(RequestedDateTime);
myList.add(beanVar);
}
request.setAttribute("list", list);
request.getRequestDispatcher("Display.jsp").forward(request, response);
在jsp: -
使用此标记
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
使用forEach
<table>
<c:forEach items="${list}" var="item">
<tr>
<td>${item.getUniqueId()}</td>
<td>${item.getClientId()}</td>
<td>${item.getConnectionStatus()}</td>
<td>${item.getRequestDateTime()}</td>
</tr>
</c:forEach>
</table>