用jsp展示数据库的商品:

来源:互联网 发布:剑三dbm数据导入失败 编辑:程序博客网 时间:2024/05/21 06:33
创建ListServlet层:


package cn.itcast.web;


public class ListServlet extends HttpServlet {
private static final long serialVersionUID = 1L;


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

try {
//直接调用servlet
ServiceDemo sd = new ServiceDemo();
List<Product> list = sd.findAll();
//把数据存到request的域中
request.setAttribute("qqq", list);
//请求转发带给jsp显示
request.getRequestDispatcher("/list.jsp").forward(request, response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}


}




创建list.jsp层
<%@page import="domain.Product"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>




<table border="1" align="center" width="500px" height="80px">
<tr>
<td>商品编号</td>
<td>商品名称</td>
<td>商品价格</td>
<td>商品描述</td>
</tr>
<%
List<Product> list=(List<Product>)request.getAttribute("list");
if(list!= null){
for(Product p :list){
out.print("<tr>");
out.print("<td>"+p.getId()+"</td>");
out.print("<td>"+p.getPname()+"</td>");
out.print("<td>"+p.getPrice()+"</td>");
out.print("<td>"+p.getPdesc()+"</td>");
out.print("</tr>");
}
}
%>
</table>
</body>
</html>




调用service层、dao层已省略、数据库已省略。
原创粉丝点击