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