用JSP显示数据库结果
我有一个控制器servlet,它将请求转发给模型servlet。现在,当模型从数据库获得结果时,我将其转发给jsp。我不确定在jsp中写什么,因为它需要显示customerList表。下面是我的模型servlet的一部分:用JSP显示数据库结果,jsp,servlets,Jsp,Servlets,我有一个控制器servlet,它将请求转发给模型servlet。现在,当模型从数据库获得结果时,我将其转发给jsp。我不确定在jsp中写什么,因为它需要显示customerList表。下面是我的模型servlet的一部分: protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
Connection connection = getDatabaseConnection();
request.setAttribute("customerList", getCustomerList(connection));
closeDatabaseConnection(connection);
}
private Vector<Customer> getCustomerList(Connection con)
{
String sqlStr =
"SELECT * " +
"FROM Customer " +
"ORDER BY Name";
PreparedStatement stmt = null;
ResultSet rs = null;
Vector<Customer> customers = new Vector<Customer>();
try
{
stmt = con.prepareStatement(sqlStr);
rs = stmt.executeQuery();
while (rs.next())
{
Customer customer = new Customer();
customer.setId(rs.getInt("Id"));
customer.setName(rs.getString("Name"));
customer.setAddress(rs.getString("Address"));
customers.add(customer);
}
rs.close();
stmt.close();
}
catch (SQLException sqle)
{
sqle.printStackTrace();
}
finally
{
return customers;
}
protectedvoidprocessrequest(HttpServletRequest请求,HttpServletResponse响应)
抛出ServletException、IOException
{
连接=getDatabaseConnection();
setAttribute(“customerList”,getCustomerList(connection));
关闭数据库连接(连接);
}
私有向量getCustomerList(连接con)
{
字符串sqlStr=
“选择*”+
“来自客户”+
“按名称排序”;
PreparedStatement stmt=null;
结果集rs=null;
向量客户=新向量();
尝试
{
stmt=con.preparest陈述(sqlStr);
rs=stmt.executeQuery();
while(rs.next())
{
客户=新客户();
customer.setId(rs.getInt(“Id”);
customer.setName(rs.getString(“Name”);
customer.setAddress(rs.getString(“地址”);
客户。添加(客户);
}
rs.close();
stmt.close();
}
捕获(SQLException sqle)
{
printStackTrace();
}
最后
{
返回客户;
}
使用标记。如果您的servletcontainer不支持它(例如Tomcat),则需要插入/WEB-INF/lib
。然后根据其文档在JSP页面顶部声明
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
顺便说一句,
不是必需的,但如果它涉及用户控制的输入,则很有用,因为它可以防止XSS攻击
也就是说,您的JDBC部分可以做得更好。它仍然对异常情况下的资源泄漏非常敏感
另见:
<table>
<c:forEach items="${customerList}" var="customer">
<tr>
<td><c:out value="${customer.id}" /></td>
<td><c:out value="${customer.name}" /></td>
<td><c:out value="${customer.address}" /></td>
</tr>
</c:forEach>
</table>