java商品展示页面代码_java学习(十四)实现商品的展示、curd以及分页展示
本文主要完成使用jdbc完成購物網(wǎng)站中實(shí)現(xiàn):展示所有商品、添加商品、刪除商品、修改單個(gè)商品、刪除多個(gè)商品、分頁展示的功能實(shí)現(xiàn)。
1.展示所有商品
本章節(jié)主要實(shí)現(xiàn)點(diǎn)擊首頁上展示所有商品的超鏈接,實(shí)現(xiàn)在頁面上展示所有的商品信息。
1.1創(chuàng)建數(shù)據(jù)庫和表
create database day14;
use day14;
create table `product` (
`pid` varchar (96),
`pname` varchar (150),
`market_price` double ,
`shop_price` double ,
`pimage` varchar (600),
`pdate` date ,
`pdesc` varchar (765)
);
INSERT INTO `product` VALUES('1','小米 4c 標(biāo)準(zhǔn)版','1399','1299','products/1/c_0001.jpg','2015-11-02','小米 4c 標(biāo)準(zhǔn)版 全網(wǎng)通 白色 移動(dòng)聯(lián)通電信4G手機(jī) 雙卡雙待');
INSERT INTO `product` VALUES('10','華為 Ascend Mate7','2699','2599','products/1/c_0010.jpg','2015-11-02','華為 Ascend Mate7 月光銀 移動(dòng)4G手機(jī) 雙卡雙待雙通6英寸高清大屏,纖薄機(jī)身,智能超八核,按壓式指紋識(shí)別!!選擇下方“移動(dòng)老用戶4G飛享合約”,無需換號(hào),還有話費(fèi)每月返還!');
INSERT INTO `product` VALUES('11','vivo X5Pro','2399','2298','products/1/c_0014.jpg','2015-11-02','移動(dòng)聯(lián)通雙4G手機(jī) 3G運(yùn)存版 極光白【購機(jī)送藍(lán)牙耳機(jī)+藍(lán)牙自拍桿】新升級(jí)3G運(yùn)行內(nèi)存·雙2.5D弧面玻璃·眼球識(shí)別技術(shù)');
INSERT INTO `product` VALUES('12','努比亞(nubia)My 布拉格','1899','1799','products/1/c_0013.jpg','2015-11-02','努比亞(nubia)My 布拉格 銀白 移動(dòng)聯(lián)通4G手機(jī) 雙卡雙待【嗨11,下單立減100】金屬機(jī)身,快速充電!布拉格相機(jī)全新體驗(yàn)!');
INSERT INTO `product` VALUES('13','華為 麥芒4','2599','2499','products/1/c_0012.jpg','2015-11-02','華為 麥芒4 晨曦金 全網(wǎng)通版4G手機(jī) 雙卡雙待金屬機(jī)身 2.5D弧面屏 指紋解鎖 光學(xué)防抖');
INSERT INTO `product` VALUES('14','vivo X5M','1899','1799','products/1/c_0011.jpg','2015-11-02','vivo X5M 移動(dòng)4G手機(jī) 雙卡雙待 香檳金【購機(jī)送藍(lán)牙耳機(jī)+藍(lán)牙自拍桿】5.0英寸大屏顯示·八核雙卡雙待·Hi-Fi移動(dòng)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 金色 移動(dòng)聯(lián)通電信4G手機(jī)長(zhǎng)期省才是真的省!點(diǎn)擊購機(jī)送費(fèi)版,月月送話費(fèi),月月享優(yōu)惠,暢享4G網(wǎng)絡(luò),就在聯(lián)通4G!');
1.2 新建項(xiàng)目,導(dǎo)入jar包,創(chuàng)建包結(jié)構(gòu)
其中導(dǎo)入的jar包
驅(qū)動(dòng)文件
dbutils
c3p0
jstl和standard
beanutils
包結(jié)構(gòu)中需要增加工具類包
utils工具類:datasourceutils
導(dǎo)入c3p0的配置文件
1.3 創(chuàng)建Product對(duì)象
在domain包內(nèi)創(chuàng)建Product.java文件,并生成get/set方法
package com.itcast.domain;
import java.util.Date;
public class Product {
private String pid;
private String pname;
private Double market_price;
private Double shop_price;
private String pimage;
private Date pdate;
private String pdesc;
...
各屬性的get/set方法
}
1.4 創(chuàng)建index.jsp文件
展示所有商品
1.5 創(chuàng)建FindAllServlet文件
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//調(diào)用service查詢所有商品
List plist = null;
try {
plist = new ProductService().findAll();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//將List放入request域中
request.setAttribute("list", plist);
//請(qǐng)求轉(zhuǎn)發(fā)
request.getRequestDispatcher("/product_list.jsp").forward(request, response);
}
1.6 創(chuàng)建ProductService
public class ProductService {
/**
* 查詢所有商品
* @return list
* @throws SQLException
*/
public List findAll() throws SQLException {
return new ProductDao().findAll();
}
}
1.7 創(chuàng)建ProductDao
public class ProductDao {
public List findAll() throws SQLException {
QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "select * from product";
return qr.query(sql, new BeanListHandler<>(Product.class));
}
}
1.8 創(chuàng)建product_list.jsp文件
...
| ${p.pid } | ${p.pname } | ${p.market_price } | ${p.shop_price } | ${p.pdesc } | 修改|刪除 |
2. 添加商品
本案例實(shí)現(xiàn)在index.jsp頁面增加一個(gè)超鏈接,點(diǎn)擊跳轉(zhuǎn)到另一頁面,用于填寫商品信息,點(diǎn)擊保存按鈕,將商品保存在數(shù)據(jù)庫中。
2.1 修改index.jsp文件
在頁面上增加“增加商品信息”的內(nèi)容
增加商品信息
2.2 創(chuàng)建add.jsp文件
主要完成form的action配置和input的name屬性配置,形成增加商品信息的表單。
| 商品名稱 | |
| 市場(chǎng)價(jià) | |
| 超市價(jià) | |
| 商品描述 | |
2.3 自動(dòng)生成ID值
在添加商品時(shí),需要讓商品生產(chǎn)自動(dòng)的id值,因此,需要使用如下代碼
public class UUIDUtils {
public static String getId() {
return UUID.randomUUID().toString().replace("-", "").toUpperCase();
}
}
該段代碼會(huì)根據(jù)系統(tǒng)和硬件,自動(dòng)生成包含"-"字符的32位字符串ID值。
2.4 創(chuàng)建addproductservlet文件
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//設(shè)置編碼,因?yàn)榻邮苷?qǐng)求中含有中文
request.setCharacterEncoding("utf-8");
//1.封裝數(shù)據(jù)
Product p = new Product();
try {
BeanUtils.populate(p, request.getParameterMap());
//1.1 設(shè)置pid
p.setPid(UUIDUtils.getId());
//1.2設(shè)置時(shí)間
p.setPdate(new Date());
//2.調(diào)用service完成添加
new ProductService().addProduct(p);
//3.頁面跳轉(zhuǎn)
//請(qǐng)求轉(zhuǎn)發(fā)
request.getRequestDispatcher("/findAll").forward(request, response);
}catch (Exception e) {
e.printStackTrace();
request.setAttribute("msg", "添加商品失敗");
request.getRequestDispatcher("/msg.jsp").forward(request, response);
}
}
在生成addproductservlet文件時(shí),當(dāng)添加商品失敗時(shí),為了增強(qiáng)用戶體驗(yàn),增加msg.jsp用于提醒用戶。
${msg }
2.5 ProductService實(shí)現(xiàn)商品添加
public void addProduct(Product p) throws SQLException {
new ProductDao().addProduct(p);
}
2.6 創(chuàng)建addProduct方法
public void addProduct(Product p) throws SQLException {
QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "insert into product(pid,pname,market_price,shop_price,pdate,pdesc) values(?,?,?,?,?,?)";
qr.update(sql, p.getPid(),p.getPname(),p.getMarket_price(),
p.getShop_price(),p.getPdate(),p.getPdesc());
}
2.7 令牌機(jī)制
有表單使用的時(shí)候,若使用請(qǐng)求轉(zhuǎn)發(fā)會(huì)出現(xiàn)重復(fù)提交的問題,因此需要使用如下兩種方法:
1.重定向;
2.令牌機(jī)制
2.7.1 令牌機(jī)制原理
服務(wù)器端在處理到達(dá)的request之前,會(huì)將request中的Token值與保存在當(dāng)前用戶session中的令牌值進(jìn)行比較,看是否匹配。在處理完該request后,且在response發(fā)送給客戶端之前,將會(huì)產(chǎn)生一個(gè)新的Token,該Token除傳給客戶端以外,也會(huì)將用戶session中保存的舊的Token進(jìn)行替換。這樣,如果用戶會(huì)退到剛才的提交頁面并再次提交的話,客戶端傳過來的Token值和服務(wù)器端的不一致,從而有效地防止了重復(fù)提交地發(fā)生。
2.7.2 實(shí)施過程
在添加頁面上隨機(jī)生成一個(gè)字符串,放入session中一份,放入表單中一份,提交的時(shí)候在后臺(tái)獲取這兩個(gè)token,然后移除session中的token(只使用一次),然后判斷兩個(gè)token是否一致,若不一致就是重復(fù)提交了。
2.7.3 應(yīng)用實(shí)例
在UUIDUtils.java文件中增加生成隨機(jī)碼方法
public static String getCode() {
return getId();
}
在add.jsp文件中,增加生成session中的token的方法
String code = UUIDUtils.getCode();
//將code放入到session 后臺(tái)進(jìn)行驗(yàn)證
session.setAttribute("s_token", code);
//將code放入到pagecontext域中
pageContext.setAttribute("r_code", code);
%>
......
在AddProductServlet中封裝數(shù)據(jù)前對(duì)兩個(gè)token進(jìn)行校驗(yàn)
//令牌機(jī)制
//獲取session中令牌和提交過來的令牌
String r_token = request.getParameter("r_token");
String s_token = (String) request.getSession().getAttribute("s_token");
//移除session中的令牌
request.getSession().removeAttribute("s_token");
//比較兩個(gè)令牌
if(s_token == null || !s_token.equals(r_token)) {
//已經(jīng)提交過了生成錯(cuò)誤提示信息放入到request域中,傳給msg.jsp
request.setAttribute("msg", "商品已經(jīng)保存");
request.getRequestDispatcher("/msg.jsp").forward(request, response);
return;
}
3. 修改商品信息
當(dāng)需要對(duì)商品信息進(jìn)行更改時(shí),點(diǎn)擊表單中的修改命令,網(wǎng)頁應(yīng)該跳轉(zhuǎn)至edit.jsp文件,將原來的信息進(jìn)行展示,修改之后保存。因此為了實(shí)現(xiàn)修改商品,首先必須完成查詢操作。
3.1 步驟分析
3.1.1 查詢步驟
創(chuàng)建修改超鏈接
修改
創(chuàng)建getProductById方法
1.獲取商品pid;
2.通過pid獲取商品,返回product對(duì)象;
3.將product放入到request域中,請(qǐng)求轉(zhuǎn)發(fā)到edit.jsp中進(jìn)行修改
3.1.2 修改步驟
edit.jsp已經(jīng)將商品的所有信息展示出來
需要將商品的id通過隱藏域放入表單中;
點(diǎn)擊保存,跳轉(zhuǎn)到editProductServlet;
在editProductServlet需要完成
1.封裝數(shù)據(jù);
2.調(diào)用dervice完成修改更新操作;
3.頁面跳轉(zhuǎn)到FindAllServlet(重定向)
3.2 查詢實(shí)現(xiàn)
3.2.1 創(chuàng)建超鏈接
創(chuàng)建修改的超鏈接,將原來的
修改|刪除修改為
修改|刪除
3.2.2 創(chuàng)建GetProductByIdServlet.java文件
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//設(shè)置編碼,因?yàn)閭魅氲臄?shù)據(jù)中米有漢字,因此無需轉(zhuǎn)碼
//獲取商品的Id
String pid = request.getParameter("pid");
//調(diào)用service通過id獲取商品
Product p=null;
try {
p = new ProductService().getProductById(pid);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//將product放入request域中,請(qǐng)求轉(zhuǎn)發(fā)到edit.jsp
request.setAttribute("bean", p);
request.getRequestDispatcher("/edit.jsp").forward(request, response);
}
3.2.3 在服務(wù)層獲取dao層數(shù)據(jù)
public Product getProductById(String pid) throws SQLException {
return new ProductDao().getProductById(pid);
}
3.2.4 dao層獲取數(shù)據(jù)
public Product getProductById(String pid) throws SQLException {
QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "select * from product where pid=?";
return qr.query(sql, new BeanHandler<>(Product.class), pid);
}
3.2.5 創(chuàng)建edit.jsp文件
在該文件中已經(jīng)使用request域中的product數(shù)據(jù),因此,value值為${bean.***}
| 商品名稱 | |
| 市場(chǎng)價(jià) | |
| 超市價(jià) | |
| 商品描述 | |
3.3 修改實(shí)現(xiàn)
3.3.1 創(chuàng)建EditProductServlet文件
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//設(shè)置編碼
request.setCharacterEncoding("utf-8");
//封裝數(shù)據(jù)
Product p = new Product();
try {
BeanUtils.populate(p, request.getParameterMap());
//調(diào)用service完成更新
new ProductService().updateProduct(p);
//重定向FindAllServlet
response.sendRedirect(request.getContextPath()+"/FindAll");
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("msg", "未能完成更新,出錯(cuò)了");
request.getRequestDispatcher("/msg.jsp").forward(request, response);
}
}
3.3.2 在服務(wù)層獲取dao層數(shù)據(jù)
public void updateProduct(Product p) throws SQLException {
new ProductDao().updateProductById(p);
}
3.3.3 dao層獲取數(shù)據(jù)
public void updateProductById(Product p) throws SQLException {
QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "update set pname = ?,market_price = ?,shop_price = ?,pdesc = ? where pid = ?";
qr.update(sql, p.getPname(),p.getMarket_price(),p.getShop_price(),
p.getPdesc(),p.getPid());
}
最終的錯(cuò)誤信息會(huì)顯示在msg.jsp文件中。
4.刪除商品
4.1步驟分析
給刪除添加事件
點(diǎn)擊刪除,觸發(fā)單擊事件,彈出提示,confirm();
點(diǎn)擊確定,刪除商品
location.href="/day14/deleteProductById?pid=?"相當(dāng)于超鏈接
deleteProductById實(shí)現(xiàn)
1.獲取商品id
2.調(diào)用service完成刪除
3.頁面重定向到findallservlet
4.2 代碼實(shí)現(xiàn)
給刪除添加超鏈接
刪除
添加單擊事件
function deleteP(obj){
if(confirm("你真的不要我了嗎")){
location.href="${pageContext.request.contextPath }/deleteProductById?pid="+obj;
}
}
創(chuàng)建deleteProductByIdServelet文件
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//獲取商品Id
String pid = request.getParameter("pid");
//調(diào)用service完成商品刪除
try {
new ProductService().deleteProductById(pid);
} catch (SQLException e) {
e.printStackTrace();
request.setAttribute("msg", "你沒能把我刪除掉哦,這是緣分");
request.getRequestDispatcher("/msg.jsp").forward(request, response);
return;
}
//重定向
response.sendRedirect(request.getContextPath()+"/findAll");
}
在服務(wù)層獲取dao層數(shù)據(jù)
public void deleteProductById(String pid) throws SQLException {
new ProductDao().deleteProductById(pid);
dao層獲取數(shù)據(jù)庫數(shù)據(jù)
public void deleteProductById(String pid) throws SQLException {
QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "delete from product where pid = ?";
qr.update(sql, pid);
}
5.刪除多個(gè)商品
5.1 步驟分析
1.給每一個(gè)商品添加復(fù)選框,同時(shí)添加name屬性,值為"pid",value為當(dāng)前商品的pid;
2.點(diǎn)擊刪除選中,需要將勾選上的商品的id提交給后臺(tái)
1)request.getParameterValues("pid");
2)必須把所有的商品放入一個(gè)表單中
3)給刪除標(biāo)簽添加單擊事件,需要先獲取表單,調(diào)用表單的submit()方法。
3.創(chuàng)建delCheckedServlet
1)獲取商品id(String[] ids);
2)調(diào)用service完成刪除操作; 3)頁面重定向FindAllServlet
5.2 前臺(tái)實(shí)現(xiàn)
增加復(fù)選框,為每一個(gè)對(duì)象添加name屬性,實(shí)現(xiàn)全選功能和按鈕單擊事件功能
| pid商品圖片商品名稱市場(chǎng)價(jià)超市價(jià)商品描述操作 | |||||||
| ${p.pid } | ${p.pname } | ${p.market_price } | ${p.shop_price } | ${p.pdesc } | 修改 | 刪除 | ||
function deleteP(obj){
if(confirm("你真的不要我了嗎")){
location.href="${pageContext.request.contextPath }/deleteProductById?pid="+obj;
}
}
function checkAll(obj){
var arr=document.getElementsByName("pid");
for(var i=0; i
arr[i].checked = obj.checked;
}
}
function delChecked(){
document.getElementById("formId").submit();
}
5.3 后臺(tái)實(shí)現(xiàn)
創(chuàng)建DeleteCheckedProductServlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//獲取id
String[] ids = request.getParameterValues("pid");
//調(diào)用service完成刪除
try {
new ProductService().deleteCheckedProducts(ids);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//重定向
response.sendRedirect(request.getContextPath()+"/findAll");
}
在ProductService中創(chuàng)建刪除方法
public void deleteCheckedProducts(String[] ids) throws SQLException {
ProductDao pDao = new ProductDao();
for(String pid:ids) {
pDao.deleteProductById(pid);
}
6.多條件查詢
6.1 步驟分析
1.在頁面增加表單和查詢按鈕;
2.提交路徑findproductbycondition:
1)獲取兩個(gè)條件;
2)調(diào)用service完成查詢,返回值為L(zhǎng)ist類型;
3)將List放入request域中,請(qǐng)求轉(zhuǎn)發(fā);
3.productdao難點(diǎn)在于sql語句:
select * from product where 1=1
若商品名不為空 and pname like...
若商品名不為空 and pdesc like ...
總結(jié)
以上是生活随笔為你收集整理的java商品展示页面代码_java学习(十四)实现商品的展示、curd以及分页展示的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java session 是什么意思_J
- 下一篇: java ee domain作用_jav