Show all products
Requirements:
Click the hyperlink on the home page to display all product information on the page
Step Analysis:
1. Databases and Tables
Huawei Ascend Mate7 Moonlight Silver Mobile 4G Mobile Phone Dual SIM Dual Standby Dual Pass 6-inch HD Large Screen, Slim Body, Smart Super Octa Core, Press Fingerprint Identification! !Choose the "4G Flying Contract for Old Mobile Users" below, there is no need to change the number, and the call fee will be refunded every month! ');
INSERT INTO `product` VALUES('11','vivo X5Pro','2399','2298','products/1/c_0014.jpg','2015-11-02','Mobile Unicom dual 4G mobile phone 3G transport Aurora White [Buy the machine to send Bluetooth headset + Bluetooth selfie stick] newly upgraded 3G running memory Dual 2.5D curved glass Eyeball recognition technology');
INSERT INTO `product` VALUES('12','Nubia ( nubia) My Prague','1899','1799','products/1/c_0013.jpg','2015-11-02','Nubia (nubia) My Prague Silver Mobile Unicom 4G mobile phone dual card dual standby [Hi 11, 100 off when you place an order] Metal body, fast charging! A new experience for Prague cameras!');
INSERT INTO `product` VALUES('13','Huawei Maimang 4','2599','2499', 'products/1/c_0012.jpg','2015-11-02','Huawei Maimang 4 Chenxi Gold Full Netcom Version 4G Mobile Phone Dual SIM Dual Standby Metal Body 2.5D Curved Screen Fingerprint Unlock Optical Image Stabilization');
INSERT INTO `product` VALUES('14','vivo X5M','1899','1799','products/1/c_0011.jpg','2015-11-02','vivo X5M mobile 4G mobile phone dual card dual standby champagne gold [purchase free Bluetooth headset + Bluetooth selfie stick] 5.0-inch large screen display, eight-core dual-card dual standby, Hi-Fi mobile KTV') ;
INSERT INTO `product` VALUES('15','Apple iPhone 6 (A1586)','4399','4288','products/1/c_0015.jpg','2015-11-02','Apple iPhone 6 (A1586) 16GB Gold Mobile Unicom Telecom 4G mobile phone is the real saving in the long term! Click on the free version to purchase the phone, send the phone bill every month, enjoy discounts every month, and enjoy the 4G network, just in China Unicom 4G!');
2. Create a new project
3. Import the jar package
driver dbutils c3p0 jstl beanutils
4. Package structure
Utils tool class: datasourceutils
import c3p0 configuration file
5. Create a new home page index.jsp
add a hyperlink
6. Click on the hyperlink to send a servlet (FindAllServlet)
7.FindAllServlet:
Call service, query all products Return value: list
Put the list in the request field and request to forward product_list.jsp
8. Put the pictures required for the content into the project
Code:
index.jsp:
<%@ 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>
<h2><a href="${pageContext.request.contextPath }/findAll">展示所有商品</a></h2>
</body>
</html>
-------------------------------------------------------------------------------
FindAllServlet:
package com.feizhu.web.servlet;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.feizhu.domain.Product;
import com.feizhu.service.ProductService;
/**
* 展示所有商品
*/
public class FindAllServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//调用service 查询所有商品 返回值list
List<Product> plist = null;
try {
plist = new ProductService().findAll();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//将list放入request域中
request.setAttribute("list", plist);
//请求转发
request.getRequestDispatcher("/product_list.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
----------------------------------------------------------------------
ProductService:
package com.feizhu.service;
import java.sql.SQLException;
import java.util.List;
import com.feizhu.dao.ProductDao;
import com.feizhu.domain.Product;
public class ProductService {
/**
* 查询所有商品
* @return list集合
* @throws SQLException
*/
public List<Product> findAll() throws SQLException {
return new ProductDao().findAll();
}
}
----------------------------------------------------------------------------------
Product:
package com.feizhu.domain;
import java.util.Date;
public class Product {
/**
* `pid` varchar (96),
`pname` varchar (150),
`market_price` double ,
`shop_price` double ,
`pimage` varchar (600),
`pdate` date ,
`pdesc` varchar (765)
*/
private String pid;
private String pname;
private Double market_price;
private Double shop_price;
private String pimage;
private Date pdate;
private String pdesc;
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public Double getMarket_price() {
return market_price;
}
public void setMarket_price(Double market_price) {
this.market_price = market_price;
}
public Double getShop_price() {
return shop_price;
}
public void setShop_price(Double shop_price) {
this.shop_price = shop_price;
}
public String getPimage() {
return pimage;
}
public void setPimage(String pimage) {
this.pimage = pimage;
}
public Date getPdate() {
return pdate;
}
public void setPdate(Date pdate) {
this.pdate = pdate;
}
public String getPdesc() {
return pdesc;
}
public void setPdesc(String pdesc) {
this.pdesc = pdesc;
}
}
----------------------------------------------------------------------------
ProductDao:
package com.feizhu.dao;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import com.feizhu.domain.Product;
import com.feizhu.utils.DataSourceUtils;
public class ProductDao {
/**
* 查询所有商品
*
* @return
* @throws SQLException
*/
public List<Product> findAll() throws SQLException {
QueryRunner qr= new QueryRunner(DataSourceUtils.getDataSource());
String sql="select * from product";
return qr.query(sql, new BeanListHandler<>(Product.class));
}
}
----------------------------------------------------------------------------
Tools:
package com.feizhu.utils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class DataSourceUtils {
private static ComboPooledDataSource ds=new ComboPooledDataSource();
private static ThreadLocal<Connection> tl=new ThreadLocal<>();
/**
*获取数据源
* @return 连接
*/
public static DataSource getDataSource() {
return ds;
}
/**
* 从 当前线程上获取连接
* @return
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
Connection conn=tl.get();
if(conn==null) {
//First get Create a connection and bind the current thread
conn=ds .getConnection ();
//Bind
tl.set(conn);
}
return conn;
}
/**
* Release the connection
* @param conn connection
*/
public static void closeConn(Connection conn) {
if(conn!=null) {
try {
conn.close();
//Unbind from the current thread
} catch (SQLException e) {
e.printStackTrace();
}
conn=null;
}
}
/**
*release statement executor
* @param st executor
*/
public static void closeStatement(PreparedStatement st) {
if(st!= null) {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
st=null;
}
}
/**
*release the result set
* @param rs result set
*/
public static void closeResultSet(ResultSet rs) {
if(rs!=null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs=null;
}
}
/**
*
* @param conn
* @param st
* @param rs
*/
public static void closeRouse(Connection conn,PreparedStatement st,ResultSet rs) {
closeRouse(st,rs);
closeConn(conn);
}
public static void closeRouse(PreparedStatement st,ResultSet rs) {
closeResultSet(rs);
closeStatement(st);
}
/**
* Open transaction
* @throws SQLException
*/
public static void startTransaction() throws SQLException {
//Get connection//Open transaction
getConnection().setAutoCommit(false);
}
//Submit things
public static void commitAndClose() {
//Get connection
try {
Connection conn=getConnection();
//Submit things
conn.commit();
//Release resources
conn.close();
//Unbind
tl .remove();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* transaction rollback
* @throws SQLException
*/
// transaction submission
public static void rollbackAndClose() {
// get connection
try {
Connection conn=getConnection( );
//Things are rolled back
conn.rollback();
//Release resources
conn.close();
//Unbind
tl.remove();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
-----------------------------------------------------------------------
product_list.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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="88%">
<tr>
<th>pid</th>
<th>商品图片</th> <th>operation</th> <th>product description</th> <th>market price</th> <th>market price</th>
<th>product name</th>
</tr>
<c:forEach items="${list }" var="p">
<tr>
<td width="8%">${p.pid }</td>
<td width="8%"><img alt="" src="${pageContext.request.contextPath}/${ p.pimage}" width="80"></td>
<td width="8%">${p.pname }</td>
<td width="8%">${p.market_price }</td>
<td width="8%">${p.shop_price }</td>
<td >${p.pdesc }</td>
<td width="8%">
修改|删除
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
-----------------------------------Show results------------- ------------------------