使用jsp查询所有商品案例实现
- 创建表product
- 项目目录(按下图导入jar包、c3p0-config.xml)
- 创建jsp页面
<%@page import="com.oracle.bean.Product"%>
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="/jsptest/product">点击查看商品</a>
<hr>
<%
ArrayList<Product> arr = (ArrayList<Product>)request.getAttribute("list");
%>
<table border="1px" width="60%" height="200px" align="center">
<tr>
<th>商品的id</th>
<th>商品的名称</th>
<th>商品的价格</th>
<th>商品的描述</th>
</tr>
<%
if(arr!=null){
for(Product p: arr){
%>
<tr>
<td><%=p.getId() %></td>
<td><%=p.getPname() %></td>
<td><%=p.getPrice() %></td>
<td><%=p.getPdesc() %></td>
</tr>
<%
}
}
%>
</table>
</body>
</html>
- 创建product bean Product.java
package com.oracle.bean;
public class Product {
private int id;
private String pname;
private double price;
private String pdesc;
public Product(int id, String pname, double price, String pdesc) {
super();
this.id = id;
this.pname = pname;
this.price = price;
this.pdesc = pdesc;
}
public Product() {
super();
// TODO Auto-generated constructor stub
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getPdesc() {
return pdesc;
}
public void setPdesc(String pdesc) {
this.pdesc = pdesc;
}
}
- 创建ProductServlet
package com.oracle;
import java.util.List;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import com.oracle.bean.Product;
import com.oracle.utils.DataSourceUtils;
public class ProductServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
//查询数据库当中的所有数据
QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "select * from product";
List<Product> list = qr.query(sql, new BeanListHandler<>(Product.class));
//把list放入域对象中
request.setAttribute("list", list);
//请求转发到aa.jsp中
request.getRequestDispatcher("/aa.jsp").forward(request, response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
- 效果
访问aa.jsp页面:
点击超链接查询商品:
注:项目编码问题的解决参考本博客的使用filter解决项目编码问题一文