Servlet+JDBC+商品列表查詢和修改

代碼倉庫+文檔:https://gitee.com/DerekAndroid/ServletJDBC.git

分析:

效果:

http://localhost:8080/ServletJDBC_war_exploded/product?method=findAll

1.商品查詢
	需求:有一個頁面上面有一個超鏈接[查詢所有商品],點擊[查詢所有商品],會把數據庫中的所有商品信息查詢出來,並且展示在表格中
		
	如何在一個servlet中判斷執行哪個方法:
		doGet(request,response){
			//獲取到method的值
			//判斷method
			if("findAll".equals(method)){
				//走查詢方法
			}else if("add".equals(method)){
				//走添加方法
			}
		}
		
		
		//定義查詢方法
		//定義增加方法
		......
		
		
		
	步驟分析:
		1.創建數據庫和表結構
		2.創建動態的web項目,創建包結構,導入項目需要的資源
		3.創建一個首頁,上面有一個'查詢所有商品'的超鏈接,點擊鏈接後向servlet發送請求    ${pageContext.request.contextPath}/findAll?method=findAll
		4.servlet的操作
			//獲取method
			//判斷當前method是哪個請求(增刪改查)
			//編寫具體請求的方法
			//調用service和dao完成查詢數據庫所有商品的操作
			//返回一個list結合
			//把當前的list放入request域對象中
			//請求轉發到jsp解析
2.增加商品
	需求:在首頁有個[增加商品]的超鏈接,點擊超鏈接後,能把用戶錄入的數據保存到數據庫
	步驟分析:
		1.在首頁加一個[添加商品]的超鏈接 ${pageContext.request.contextPath}/product?method=addUI
		2.點擊超鏈接向servlet發送請求 (請求轉發到product.jsp中  防止product.jsp直接暴露在地址欄中)
		3.用戶錄入數據後點擊增加按鈕 向servlet發送請求     
									${pageContext.request.contextPath}/product?method=add(有丟失參數的風險)
						  解決方式:<input type="hidden" name="method" value="add">
		4.在add方法中
			//獲取表單中的所有數據  map
			//創建product
			//把map中的數據拷貝到product中
			//把pid(UUID)和pdate存放到Product中
			//調用service和dao完成數據保存操作
			//請求轉發到查詢所有的鏈接上   /product?method=findAll
			//如果有異常需要請求轉發到error.jsp頁面
3.修改商品
	需求:點擊列表中商品後面的修改按鈕,就可以對當前商品信息進行修改,
	跳轉到修改的表單頁面(數據是已經填寫好的),在此基礎上進行修改,點擊修改按鈕後,在數據庫中更新該條數據
	
	
4.刪除商品
	需求:點擊列表中商品後面的刪除按鈕,點擊後,彈出[確認刪除該條商品嗎?]的提示,點擊確認,則刪除該條商品,點擊取消,不執行刪除
5.批量刪除商品

6.模糊查詢

7.分頁

sql表

CREATE DATABASE day17;
USE day17;
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!');

Servlet

package com.itheima.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import com.itheima.bean.Product;
import com.itheima.service.ProductService;
import com.mysql.fabric.xmlrpc.base.Data;

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

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//解決亂碼
		request.setCharacterEncoding("utf-8");
		//獲取method
		String method = request.getParameter("method");
		//根據method判斷執行哪個方法
		if("findAll".equals(method)){
			findAll(request,response);
		}else if("addUI".equals(method)){
			addUI(request,response);
		}else if("add".equals(method)){
			add(request,response);
		}else if("edit".equals(method)){
			edit(request,response);
		}else if("update".equals(method)){
			update(request,response);
		}else if("delete".equals(method)){
			deletePro(request,response);
		}
	}
	/*
	 * 根據商品id刪除商品信息
	 */
	private void deletePro(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			//獲取pid
			String pid = request.getParameter("pid");
			//調用service和dao完成刪除商品操作
			ProductService ps = new ProductService();
			ps.deletePro(pid);
			
			//請求轉發到查詢所有的鏈接上
			request.getRequestDispatcher("/product?method=findAll").forward(request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			request.setAttribute("msg", "刪除商品失敗");
			request.getRequestDispatcher("/error.jsp").forward(request, response);
		}
	}
	/**
	 * 根據id更新商品
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			//獲取map
			Map<String, String[]> map = request.getParameterMap();
			//創建bean
			Product pro = new Product();
			//把map中的數據拷貝到bean中
			BeanUtils.populate(pro, map);
			//調用service完成數據更新
			ProductService ps = new ProductService();
			ps.updatePro(pro);
			//請求轉發到查詢所有商品的鏈接上
			request.getRequestDispatcher("/product?method=findAll").forward(request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			request.setAttribute("msg", "更新商品失敗");
			request.getRequestDispatcher("/error.jsp").forward(request, response);
		} 
	}
	/**
	 * 根據id查詢數據
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			//獲取id
			String id = request.getParameter("id");
			//調用方法查詢pro
			ProductService ps = new ProductService();
			Product pro=ps.getProByPid(id);
			
			//把pro放入request中
			request.setAttribute("pro", pro);
			//請求轉發到edit.jsp
			request.getRequestDispatcher("/edit.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("msg", "查詢單條記錄商品失敗");
			request.getRequestDispatcher("/error.jsp").forward(request, response);
		} 
	}
	/**
	 * 添加商品
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			
			//獲取前臺錄入的數據  map
			Map<String, String[]> map = request.getParameterMap();
			//創建bean
			Product pro = new Product();
			//把map中的數據拷貝到bean中
			BeanUtils.populate(pro, map);
			//把pid和pdate放入bean中
			pro.setPid(UUIDCls.getUUid());
			pro.setPdate(new Date().toLocaleString());
			//調用service完成保存操作
			ProductService ps = new ProductService();
			ps.saveProduct(pro);
			//請求轉發到查詢鏈接
			request.getRequestDispatcher("/product?method=findAll").forward(request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			request.setAttribute("msg", "添加商品失敗");
			request.getRequestDispatcher("/error.jsp").forward(request, response);
		} 
	}
	/**
	 * 防止具體的資源暴露在地址欄後面
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void addUI(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.getRequestDispatcher("/product.jsp").forward(request, response);
	}
	/**
	 * 查詢所有商品
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			//創建ProductService
			ProductService ps = new ProductService();
			//調用方法
			List<Product> list = ps.findAll();
			//把list集合放入request域對象中
			request.setAttribute("list", list);
			//請求轉發到list.jsp
			request.getRequestDispatcher("/list.jsp").forward(request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			request.setAttribute("msg", "查詢商品出現錯誤");
			request.getRequestDispatcher("/error.jsp").forward(request, response);
		}
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

 

發佈了178 篇原創文章 · 獲贊 44 · 訪問量 24萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章