0、綜合案例功能介紹 以上是在綜合案例要實現的功能。除了對數據的增刪改查功能之外,還有一些複雜的功能,如批量刪除,分頁查詢,條件查詢等功能 批量刪除功能:每條數據前都有覆選框,當我們選中多條數據並點擊批量刪除按鈕後,會發送請求到後端並刪除資料庫指定的多條數據 分頁查詢功能:當資料庫中有很多數據的時候 ...
0、綜合案例功能介紹
- 以上是在綜合案例要實現的功能。除了對數據的增刪改查功能之外,還有一些複雜的功能,如
批量刪除
,分頁查詢
,條件查詢
等功能批量刪除
功能:每條數據前都有覆選框,當我們選中多條數據並點擊批量刪除
按鈕後,會發送請求到後端並刪除資料庫指定的多條數據分頁查詢
功能:當資料庫中有很多數據的時候,我們不可能將所有的數據展示在一頁里,這個時候就需要分頁展示數據條件查詢
功能:資料庫量大的時候,我們需要精確的查詢一些想看到的數據,這個時候就需要通過條件查詢
1、查詢所有功能
- 整體流程如下圖所示
1.1、後端實現
1.1.1、dao方法實現
-
在
com.coolman.mapper.BrandMapper
介面中定義抽象方法,使用@Select
註解編寫SQL語句-
// 查詢所有品牌 @Select("select * from brand.tb_brand order by ordered") List<Brand> selectAllBrands();
-
-
由於表中有些欄位名和實體類中的屬性名沒有對應,所以要進行相關配置
-
方法1:在SQL語句中取別名
-
// 查詢所有品牌 @Select("select id, brand_name as brandName, company_name as companyName, ordered, description, status from brand.tb_brand order by ordered") List<Brand> selectAllBrands();
-
-
方法2:在
BrandMapper.xml
映射配置文件中定義結果映射,同時在使用註解開發的條件下在Mapper介面中使用ResultMap註解-
<resultMap id="brandResultMap" type="Brand"> <result property="brandName" column="brand_name" /> <result property="companyName" column="company_name" /> </resultMap>
-
//查詢所有品牌 @Select("select * from brand.tb_brand order by ordered") @ResultMap("brandResultMap") List<Brand> selectAllBrands();
-
-
方法3:在MyBatis配置文件中設置並開啟駝峰自動命名映射
-
<settings> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings>
-
-
1.1.2、service實現
-
// 查詢所有品牌 public List<Brand> selectAllBrands() { SqlSession sqlSession = MyBatisUtils.getSqlSession(); BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); List<Brand> brands = mapper.selectAllBrands(); sqlSession.close(); return brands; }
1.1.3、Servlet實現
-
package com.coolman.web.servlet; import com.alibaba.fastjson.JSON; import com.coolman.pojo.Brand; import com.coolman.service.BrandService; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; @WebServlet("/selectAllBrandsServlet") public class SelectAllBrandsServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 在這裡處理請求 // 調用服務,查詢所有 List<Brand> brands = new BrandService().selectAllBrands(); // System.out.println(brands); // 將List對象轉換為JSON字元串,傳遞給前端 String brandsJson = JSON.toJSONString(brands); // 解決中文亂碼問題,聲明字元串為JSON字元串 response.setContentType("application/json;charset=utf-8"); // 返回JSON字元串 response.getWriter().print(brandsJson); } }
1.2、前端實現
-
created() { axios.get("selectAllBrandsServlet").then( response => { // window.alert("正在請求數據"); // console.log(response.data); this.tableData = response.data; }); },
2、添加功能
- 整體流程如圖所示
2.1、後端實現
2.1.1、dao方法實現
-
// 添加品牌 @Insert("insert into brand.tb_brand values(null, #{brandName}, #{companyName}, #{ordered}, #{description}, #{status})") void addBrand(Brand brand);
2.1.2、service方法實現
-
// 添加品牌 public void addBrand(Brand brand) { SqlSession sqlSession = MyBatisUtils.getSqlSession(); BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); mapper.addBrand(brand); sqlSession.commit(); sqlSession.close(); }
2.1.3、servlet方法實現
-
package com.coolman.web.servlet; import com.alibaba.fastjson.JSON; import com.coolman.pojo.Brand; import com.coolman.service.BrandService; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintStream; @WebServlet("/addBrandServlet") public class AddBrandServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 在這裡處理請求 // 獲取ajax請求返回的json字元串 // 獲取請求體中的輸入流 ServletInputStream inputStream = request.getInputStream(); // 調用JSON的api將返回的json字元串轉換為實體類對象 Brand brand = JSON.parseObject(inputStream, Brand.class); // 調用服務保存信息 new BrandService().addBrand(brand); response.getWriter().print("ok"); } }
2.2、前端實現
-
在Vue對象中的方法屬性中添加一個功能
-
// 添加數據 addBrand(){ console.log(this.brand); axios.post("addBrandServlet", this.brand).then(response => { if (response.data == "ok") { this.dialogVisible = false; window.location.href = "brand.html"; } else { window.alert("添加失敗!"); } }) },
-
3、刪除功能
3.1、後端實現
3.1.1、dao層實現
-
// 刪除品牌 @Delete("delete from brand.tb_brand where id = #{id}") void deleteBrand(int id);
3.1.2、service層實現
-
// 刪除品牌 public void deleteBrand(int id) { SqlSession sqlSession = MyBatisUtils.getSqlSession(); BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); mapper.deleteBrand(id); sqlSession.commit(); sqlSession.close(); }
3.1.3、servlet層實現
-
package com.coolman.web.servlet; import com.coolman.service.BrandService; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/deleteBrandServlet") public class DeleteBrandServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 在這裡處理請求 // 獲取返回的id String idStr = request.getParameter("id"); int id = Integer.parseInt(idStr); // 調用服務,刪除該品牌 new BrandService().deleteBrand(id); // 返回成功刪除信息 response.getWriter().print("ok"); } }
3.2、前端實現
-
在Vue對象的method屬性中添加
deleteBrandById
方法,同時在html標簽中的點擊事件中,傳遞一個參數回來到方法中-
<el-table-column align="center" label="操作"> <template slot-scope="scope"> <el-button type="primary" @click="">修改</el-button> <el-button type="danger" @click="deleteBrandById(scope.row.id)">刪除</el-button> </template> </el-table-column>
-
// 刪除數據 deleteBrandById(id){ // 發送ajax請求 axios.get("deleteBrandServlet?id=" + id).then( response => { if (response.data == "ok") { // 刪除成功,跳轉回brand.html window.location.href = "brand.html"; } else { window.alert("刪除失敗"); } }); },
-
4、修改功能
4.1、後端實現
4.1.1、dao層實現
-
// 修改品牌 // 回顯功能,根據id查詢品牌信息 @Select("select * from brand.tb_brand where id = #{id}") Brand selectBrandById(int id); // 修改功能 @Update("update brand.tb_brand set brand_name = #{brandName}, company_name = #{companyName}, ordered = #{ordered}, " + "description = #{description},status = #{status} where id = #{id}") void updateBrandById(Brand brand);
4.1.2、service層實現
-
// 修改品牌 // 回顯功能 public Brand selectBrandById(int id) { SqlSession sqlSession = MyBatisUtils.getSqlSession(); BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); Brand brand = mapper.selectBrandById(id); sqlSession.close(); return brand; } // 修改功能 public void updateBrandById(Brand brand) { SqlSession sqlSession = MyBatisUtils.getSqlSession(); sqlSession.getMapper(BrandMapper.class).updateBrandById(brand); sqlSession.commit(); sqlSession.close(); }
4.1.3、servlet層實現
-
回顯功能
-
package com.coolman.web.servlet; import com.alibaba.fastjson.JSON; import com.coolman.pojo.Brand; import com.coolman.service.BrandService; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/selectBrandByIdServlet") public class SelectBrandByIdServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 在這裡處理請求 // 接收前端返回的id String idStr = request.getParameter("id"); int id = Integer.parseInt(idStr); // 調用服務,查詢品牌信息 Brand brand = new BrandService().selectBrandById(id); // 將Java對象轉換成json數據,返回給前端 String jsonString = JSON.toJSONString(brand); // 向前端聲明返回的數據是json數據,同時更改編碼格式防止編碼錯誤 response.setContentType("application/json;charset=utf-8"); // System.out.println(jsonString); response.getWriter().print(jsonString); } }
-
-
修改功能
-
package com.coolman.web.servlet; import com.alibaba.fastjson.JSON; import com.coolman.pojo.Brand; import com.coolman.service.BrandService; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/updateBrandByIdServlet") public class UpdateBrandByIdServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 在這裡處理請求 // 接收前端返回的json數據 // 得到輸入流 ServletInputStream inputStream = request.getInputStream(); // 待用JSON的API轉換成JAVA對象 Brand brand = JSON.parseObject(inputStream, Brand.class); // 調用服務,修改數據 new BrandService().updateBrandById(brand); // 返回修改成功信息給前端 response.getWriter().print("ok"); } }
-
4.2、前端實現
-
//修改數據 // 點擊修改按鈕後,為了增強用戶體驗,添加一個數據回顯功能 selectBrandById(id){ this.dialogVisibleUpdate = true // 發送ajax請求 axios.get("selectBrandByIdServlet?id=" + id).then(response => { // 接收後端返回的json數據 this.brand = response.data; // el-switch開關的預設值必須類型也要匹配~ this.brand.status = this.brand.status.toString(); console.log(this.brand); }); }, // 執行修改語句 updateBrandById(id){ // 發送ajax請求 axios.post("updateBrandByIdServlet", this.brand).then(response => { if (response.data == "ok") { // 跳轉到brand.html頁面 window.location.href = "brand.html"; }else { window.alert("修改失敗!") } }); },
5、servlet優化
5.1、背景
- Web層的Servlet個數太多,不利於管理和編寫
- 模塊的每一個功能都需要定義一個
servlet
,當模塊的數量多時,就很容易造成servlet
泛濫。
- 模塊的每一個功能都需要定義一個
5.2、解決方法
-
一個模塊只定義一個
servlet
,模塊中的每一個功能只需要在servlet
中定義對應的方法,如下代碼所示 -
@WebServlet("/brand/*") public class BrandServlet { //查詢所有 public void selectAll(...) {} //添加數據 public void add(...) {} //修改數據 public void update(...) {} //刪除刪除 public void delete(...) {} }
5.3、思路
- 當發送請求至
servlet
,tomcat
會自動調用service()
方法,源碼如下所示- 我們一般在自定義的
servlet
中會重寫doGet()
和doPost()
方法,當我們訪問該servlet
的時候會根據請求方式將請求分發給doGet()
或者doPost()
方法
- 我們一般在自定義的
- 那麼可以仿照這樣的請求分發的思想,在
service()
方法中根據具體的操作調用對應的方法- 如:查詢所有就調用
selectAll()
方法,添加企業信息就調用add()
方法
- 如:查詢所有就調用
5.4、具體實現
-
定義一個通用的
servlet
類,在定義其他的servlet
是不需要繼承HttpServlet
,而繼承我們定義的BaseServlet
,在BaseServlet
中調用具體servlet
(如BrandServlet
)中的對應方法,如下所示-
BaseServlet
-
public class BaseServlet extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //進行請求的分發 } }
-
-
BrandServlet
-
@WebServlet("/brand/*") public class BrandServlet extends BaseServlet { //用戶實現分頁查詢 public void selectAll(...) {} //添加企業信息 public void add(...) {} //修改企業信息 public void update(...) {} //刪除企業信息 public void delete(...) {} }
-
-
-
那麼如何在
BaseServlet
中調用對應的方法,進行請求分發呢?-
可以規定在發送請求的時候,請求資源的二級路徑(/brandServlet/selectAll)和需要調用的方法名相同,如下所示
- 查詢所有數據的路徑以後就需要寫成:
http://localhost:8080/brand-case/brandServlet/selectAll
- 添加數據的路徑以後就需要寫成:
http://localhost:8080/brand-case/brandServlet/add
- 修改數據的路徑以後就需要寫成:
http://localhost:8080/brand-case/brandServlet/update
- 刪除數據的路徑以後就需要寫成:
http://localhost:8080/brand-case/brandServlet/delete
- 查詢所有數據的路徑以後就需要寫成:
-
或者給在路徑中添加一個參數,值為對應的方法名稱,如下所示
- 查詢所有數據的路徑以後就需要寫成:
http://localhost:8080/brand-case/brandServlet?action=selectAll
- ...
- 查詢所有數據的路徑以後就需要寫成:
-
-
這樣的話,在
BaseServlet
中就需要獲取到資源的二級路徑作為方法名或者路徑中的action
參數的值,然後調用該方法
5.4.1、後端代碼
-
BaseServlet
-
package com.coolman.web.servlet; import cn.hutool.core.util.StrUtil; import com.coolman.web.servlet.BrandServlet; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class BaseServlet extends HttpServlet { @Override // tomcat中的servlet每次被調用都會執行service方法 protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 在這裡分發請求 // 1. 獲取方法名稱 // 1.1 如果請求的URL格式為 .../brandServlet?action=selectAll // 那麼獲取方法名稱則要簡單很多 // String methodName = request.getParameter("action"); // 但是在前端的ajax請求中就需要多寫一些單詞 // 1.2 如果請求的URL格式為 .../brandServlet/selectAll // 使用工具類,獲取到最後一個'/'號後面的字元串 // 1.2.1 獲取請求的URI String requestURI = request.getRequestURI(); // 1.2.2 使用工具類,獲取到最後一個'/'號後面的字元串 String methodName = StrUtil.subAfter(requestURI, "/", true); // 2. 獲取方法名稱後調用方法 // 方式1: // if ("selectAll".equals(methodName)) { // selectAll(request, response); // } else if ("add".equals(methodName)) { // add(request, response); // } else if ("delete".equals(methodName)) { // delete(request, response); // } else if ("update".equals(methodName)) { // update(request, response); // } //else if ... // 方式2: 方式1在當功能多的時候就會顯地條件判斷很冗餘 // 可以利用反射的方法,獲取到方法,然後調用對應的方法即可 try { Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class); // 再讓方法對象執行 // 暴力反射獲取位元組碼對象的時候需要去除許可權(在同一個包下,protected是可以訪問的) // method.setAccessible(true); method.invoke(this, request, response); } catch (Exception e) { e.printStackTrace(); } // catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { // e.printStackTrace(); // } } }
-
-
BrandServlet
-
package com.coolman.web.servlet; import com.alibaba.fastjson.JSON; import com.coolman.pojo.Brand; import com.coolman.service.BrandService; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; @WebServlet("/brand/*") // 不帶action //@WebServlet("/brand") // 帶action public class BrandServlet extends BaseServlet { // 查詢所有品牌 protected void selectAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 調用服務,查詢所有 List<Brand> brands = new BrandService().selectAllBrands(); // System.out.println(brands); // 將List對象轉換為JSON字元串,傳遞給前端 String brandsJson = JSON.toJSONString(brands); // 解決中文亂碼問題,聲明字元串為JSON字元串 response.setContentType("application/json;charset=utf-8"); // 返回JSON字元串 response.getWriter().print(brandsJson); } // 添加品牌 protected void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 獲取ajax請求返回的json字元串 // 獲取請求體中的輸入流 ServletInputStream inputStream = request.getInputStream(); // 調用JSON的api將返回的json字元串轉換為實體類對象 Brand brand = JSON.parseObject(inputStream, Brand.class); // 調用服務保存信息 new BrandService().addBrand(brand); response.getWriter().print("ok"); } // 刪除品牌 protected void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 獲取返回的id String idStr = request.getParameter("id"); int id = Integer.parseInt(idStr); // 調用服務,刪除該品牌 new BrandService().deleteBrand(id); // 返回成功刪除信息 response.getWriter().print("ok"); } // 根據id查詢品牌 protected void selectBrandById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 接收前端返回的id String idStr = request.getParameter("id"); int id = Integer.parseInt(idStr); // 調用服務,查詢品牌信息 Brand brand = new BrandService().selectBrandById(id); // 將Java對象轉換成json數據,返回給前端 String jsonString = JSON.toJSONString(brand); // 向前端聲明返回的數據是json數據,同時更改編碼格式防止編碼錯誤 response.setContentType("application/json;charset=utf-8"); // System.out.println(jsonString); response.getWriter().print(jsonString); } // 修改品牌信息 protected void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 接收前端返回的json數據 // 得到輸入流 ServletInputStream inputStream = request.getInputStream(); // 待用JSON的API轉換成JAVA對象 Brand brand = JSON.parseObject(inputStream, Brand.class); // 調用服務,修改數據 new BrandService().updateBrandById(brand); // 返回修改成功信息給前端 response.getWriter().print("ok"); } }
-
註意事項
BaseServlet
和BrandServlet
要放在同一個包下,否則因為BrandServlet
中的方法全都是protected
修飾的方法,必須要設置取出許可權才可調用method.setAccessible(true);
7、批量刪除
7.1、後端實現
7.1.1、dao層實現
-
BrandMapper.java
-
// 批量刪除 void deleteByIds(@Param("ids") int[] ids);
-
-
BrandMapper.xml
-
<delete id="deleteByIds"> delete from brand.tb_brand where id in <foreach collection="ids" separator="," open="(" close=")" item="id"> #{id} </foreach> </delete>
-
7.1.2、service層實現
-
// 批量刪除功能 public void deleteByIds(int[] ids) { SqlSession sqlSession = MyBatisUtils.getSqlSession(true); BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); mapper.deleteByIds(ids); sqlSession.close(); }
7.1.3、web層servlet實現
-
// 批量刪除 protected void deleteByIds(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 接收前端返回的id數組 ServletInputStream inputStream = request.getInputStream(); int[] ids = JSON.parseObject(inputStream, int[].class); // 調用服務 new BrandService().deleteByIds(ids); // 返回成功信息 response.getWriter().print("ok"); }
7.2、前端實現
-
body
中的標簽綁定好事件後,執行事件的方法-
// 批量刪除數據 deleteBatch() { this.$confirm("確定要刪除嗎?","提示", { confirmButtonText: "確定", cancelButtonText: "取消", type: "warning" }).then( () => { // 點擊確定按鈕後要執行的操作 // this.$message({ // message: "刪除成功!", // type: "success" // }); let ids = []; for (let i = 0; i < this.multipleSelection.length; i++) { // ids[i] = this.multipleSelection[i].id; ids.push(this.multipleSelection[i].id); } console.log(ids); axios.post("brand/deleteByIds", ids).then( response => { if (response.data == "ok") { window.location.href = "brand.html"; } else { this.$message({ message: "刪除失敗!", type: "error" }); } }); }); },
-
8、分頁查詢
8.1、後端實現
8.1.1、dao層實現
-
// 分頁查詢 //select * from ... limit 起始索引, 每頁條數 // select * from tb_brand limit 0, 5; // 第一頁 // // select * from tb_brand limit 5, 5; // 第二頁 // // select * from tb_brand limit 10, 5; // 第三頁 //select * from ... limit (起始索引 - 1) * 每頁條數, 每頁條數 @Select("select * from brand.tb_brand limit #{currentPage}, #{pageSize}") List<Brand> selectBrandByPage(@Param("currentPage") int currentPage, @Param("pageSize") int pageSize); // 頁碼左邊需要的總條數 @Select("select count(*) from brand.tb_brand") Integer selectSumCount();
8.1.2、service層實現
-
// 分頁功能 public PageBean<Brand> selectBrandByPage(int currentPage, int pageSize) { //select * from ... limit (起始索引 - 1) * 每頁條數, 每頁條數 currentPage = (currentPage - 1) * pageSize; SqlSession sqlSession = MyBatisUtils.getSqlSession(); BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); List<Brand> brands = mapper.selectBrandByPage(currentPage, pageSize); int totalCount = mapper.selectSumCount(); sqlSession.close(); return new PageBean<Brand>(totalCount, brands); }
8.1.3、web層servlet實現
-
// 處理分頁請求 protected void selectBrandByPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 接收前端返回的頁碼數 // pageSize int pageSize = Integer.parseInt(request.getParameter("pageSize")); // currentPage int currentPage = Integer.parseInt(request.getParameter("currentPage")); // 調用服務 PageBean<Brand> pageBean = new BrandService().selectBrandByPage(currentPage, pageSize); // 返回數據 String string = JSON.toJSONString(pageBean); response.setContentType("application/json;charset=utf-8"); response.getWriter().print(string); }
8.2、前端實現
-
created()
函數-
created() { axios.get("brand/selectBrandByPage?currentPage=" + this.currentPage + "&pageSize=" + this.pageSize).then( response => { // window.alert("正在請求數據"); // console.log(response.data); this.totalCount = response.data.totalCount; this.tableData = response.data.list; }); }
-
-
handleSizeChange(val)
函數(每一頁的數據量)-
handleSizeChange(val) { console.log(`每頁 ${val} 條`); this.pageSize = val; axios.get("brand/selectBrandByPage?currentPage=" + this.currentPage + "&pageSize=" + this.pageSize).then( response => { // window.alert("正在請求數據"); // console.log(response.data); this.tableData = response.data.list; }); }
-
-
handleCurrentChange(val)
函數(當前頁碼)-
handleCurrentChange(val) { console.log(`當前頁: ${val}`); this.currentPage = val; axios.get("brand/selectBrandByPage?currentPage=" + this.currentPage + "&pageSize=" + this.pageSize).then( response => { // window.alert("正在請求數據"); // console.log(response.data); this.tableData = response.data.list; }); }
-
9、條件查詢
9.1、後端實現
9.1.1、dao層實現
-
Mapper
介面-
// 多條件查詢 List<Brand> selectBrandByCondition(@Param("brand") Brand brand, @Param("currentPage") int currentPage, @Param("pageSize") int pageSize); // 查詢結果記錄數 int selectSearchCount(Brand brand);
-
-
Mapper
映射文件-
<select id="selectBrandByCondition" resultMap="brandResultMap"> select * from brand.tb_brand <where> <!-- 當狀態碼設置為0或1的時候,很容易出現框架自動轉換成false或true的情況;可以看作一個小bug --> <!-- 當傳入的是int型的數字 0 時,mybatis會把它當成空字元串 status != '', 0 != '' ==> '' != '' --> <if test="brand.status != null"> status = #{brand.status} </if> <if test="brand.brandName != null and brand.brandName != ''"> and brand_name like #{brand.brandName} </if> <if test="brand.companyName != null and brand.companyName != ''"> and company_name like #{brand.companyName} </if> </where> order by ordered limit #{currentPage}, #{pageSize} </select> <select id="selectSearchCount" resultType="java.lang.Integer"> select count(*) from brand.tb_brand <where> <if test="status != null"> status = #{status} </if> <if test="brandName != null and brandName != ''"> and brand_name like #{brandName} </if> <if test="companyName != null and companyName != ''"> and company_name like #{companyName} </if> </where> </select>
-
9.1.2、service層實現
-
// 多條件查詢 public PageBean<Brand> selectBrandByCondition(Brand brand, int currentPage, int pageSize) { SqlSession sqlSession = MyBatisUtils.getSqlSession(); BrandMapper mapper = sqlSession.getMapper(BrandMapper.class); if (brand.getBrandName() != null && brand.getBrandName().length() > 0) { brand.setBrandName("%" + brand.getBrandName() + "%"); } if (brand.getCompanyName() != null && brand.getCompanyName().length() > 0) { brand.setCompanyName("%" + brand.getCompanyName() + "%"); } currentPage = (currentPage - 1) * pageSize; List<Brand> brands = mapper.selectBrandByCondition(brand, currentPage, pageSize); int count = mapper.selectSearchCount(brand); sqlSession.close(); return new PageBean<>(count, brands); }
9.1.3、web層servlet實現
-
// 處理搜索請求 protected void selectBrandByCondition(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 接收前端返回的數據 int currentPage = Integer.parseInt(request.getParameter("currentPage")); int pageSize = Integer.parseInt(request.getParameter("pageSize")); ServletInputStream inputStream = request.getInputStream(); Brand brand = JSON.parseObject(inputStream, Brand.class); System.out.println("brand = " + brand); // 調用服務 PageBean<Brand> brands = new BrandService().selectBrandByCondition(brand, currentPage, pageSize); // 返回數據 String string = JSON.toJSONString(brands); response.setContentType("application/json;charset=utf-8"); response.getWriter().print(string); }
9.2、前端實現
-
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>商品列表</title> <style> .el-table .warning-row { background: oldlace; } .el-table .success-row { background: #f0f9eb; } </style> </head> <body> <div id="app"> <!--搜索表單--> <el-form :inline="true" v-model="brand" class="demo-form-inline"> <el-form-item label="當前狀態"> <el-select v-model="brand.status" placeholder="當前狀態"> <el-option label="啟用" value="1"></el-option> <el-option label="禁用" value="0"></el-option> </el-select> </el-form-item> <el-form-item label="企業名稱"> <el-input v-model="brand.companyName" placeholder="企業名稱"></el-input> </el-form-item> <el-form-item label="品牌名稱"> <el-input v-model="brand.brandName" placeholder="品牌名稱"></el-input> </el-form-item> <el-form-item> <el-button type="primary" @click="onSubmit()">查詢</el-button> </el-form-item> </el-form> <!--按鈕--> <el-row> <el-button type="danger" plain @click="deleteBatch()">批量刪除</el-button> <el-button type="primary" plain @click="dialogVisibleAdd = true">新增</el-button> </el-row> <!--添加數據對話框表單--> <el-dialog title="添加品牌" :visible.sync="dialogVisibleAdd" width="30%" > <el-form ref="form" :model="brand" label-width="80px"> <el-form-item label="品牌名稱"> <el-input v-model="brand.brandName"></el-input> </el-form-item> <el-form-item label="企業名稱"> <el-input v-model="brand.companyName"></el-input> </el-form-item> <el-form-item label="排序"> <el-input v-model="brand.ordered"></el-input> </el-form-item> <el-form-item label="備註"> <el-input type="textarea" v-model="brand.description"></el-input> </el-form-item> <el-form-item label="狀態"> <el-switch v-model="brand.status" active-value="1" inactive-value="0" ></el-switch> </el-form-item> <el-form-item> <el-button type="primary" @click="addBrand">提交</el-button> <el-button @click="dialogVisibleAdd = false">取消</el-button> </el-form-item> </el-form> </el-dialog> <!--修改數據對話框表單--> <el-dialog title="編輯品牌" :visible.sync="dialogVisibleUpdate" width="30%" > <el-form ref="form" :model="brand" label-width="80px"> <el-form-item label="品牌名稱"> <el-input v-model="brand.brandName"></el-input> </el-form-item> <el-form-item label="企業名稱"> <el-input v-model="brand.companyName"></el-input> </el-form-item> <el-form-item label="排序"> <el-input v-model="brand.ordered"></el-input> </el-form-item> <el-form-item label="備註"> <el-input type="textarea" v-model="brand.description"></el-input> </el-form-item> <el-form-item label="狀態"> <el-switch v-model="brand.status" active-value="1" inactive-value="0" ></el-switch> </el-form-item> <el-form-item> <el-button type="primary" @click="update()">提交</el-button> <el-button @click="dialogVisibleUpdate = false">取消</el-button> </el-form-item> </el-form> </el-dialog> <!--表格--> <template> <el-table :data="tableData" style="width: 100%" :row-class-name="tableRowClassName" @selection-change="handleSelectionChange" > <el-table-column type="selection" width="55"> </el-table-column> <el-table-column type="index" width="50"> </el-table-column> <el-table-column prop="brandName" label="品牌名稱" align="center" > </el-table-column> <el-table-column prop="companyName" label="企業名稱" align="center" > </el-table-column> <el-table-column prop="ordered" align="center" label="排序"> </el-table-column> <el-table-column prop="description" align="center" label="描述"> </el-table-column> <el-table-column prop="status" align="center" label="當前狀態"> <template slot-scope="scope"> <el-tag type="success" v-if="scope.row.status=='1'">啟用</el-tag> <el-tag type="danger" v-else>禁用</el-tag> </template> </el-table-column> <el-table-column align="center" label="操作"> <template slot-scope="scope"> <el-button type="primary" @click="selectBrandById(scope.row.id)">修改</el-button> <el-button type="danger" @click="deleteBrandById(scope.row.id)">刪除</el-button> </template> </el-table-column> </el-table> </template> <!--分頁工具條--> <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[5, 10, 15, 20]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="totalCount"> </el-pagination> </div> <script src="js/vue.js"></script> <script src="./js/axios-0.18.0.js"></script> <script src="element-ui/lib/index.js"></script> <link rel="stylesheet" href="element-ui/lib/theme-chalk/index.css"> <script> new Vue({ el: "#app", created() { this.selectAll(); }, data() { return { // 當前頁碼 currentPage: 1, // 總數據數 totalCount: 0, // 每一頁的數據數量 pageSize: 5, // 搜索框 // 添加數據對話框是否展示的標記 dialogVisibleAdd: false, // 修改數據對話框是否展示的標記 dialogVisibleUpdate: false, // 品牌模型數據 brand: { status: '', brandName: '', companyName: '', id:"", ordered:"", description:"" }, // 覆選框選中數據集合 multipleSelection: [], // 表格數據 tableData: [], // 頁碼數 } }, methods: { tableRowClassName({row, rowIndex}) { if (rowIndex === 1) { return 'warning-row'; } else if (rowIndex === 3) { return 'success-row'; } return ''; }, // 覆選框選中後執行的方法 handleSelectionChange(val) { this.multipleSelection = val; console.log(this.multipleSelection) }, // 查詢方法 onSubmit() { // console.log("當前頁碼:" + this.currentPage) // console.log("每頁數量:" + this.pageSize) // console.log("搜索部分信息:") // console.log(this.brand) this.selectAll(); }, selectAll() { axios.post("brand/selectBrandByCondition?currentPage=" + this.currentPage + "&pageSize=" + this.pageSize, this.brand ).then( response => { // window.alert("正在請求數據"); console.log(response.data); this.totalCount = response.data.totalCount; this.tableData = response.data.list; }); }, // 添加數據 addBrand(){ console.log(this.brand); axios.post("brand/add", this.brand).then(response => { if (response.data == "ok") { this.dialogVisible = false; window.location.href = "brand.html"; } else { window.alert("添加失敗!"); } }) }, // 刪除數據 deleteBrandById(id){ // 發送ajax請求 axios.get("brand/delete?id=" + id).then( response => { if (response.data == "ok") { // 刪除成功,跳轉回brand.html window.location.href = "brand.html"; } else { window.alert("刪除失敗"); } }); }, //修改數據 // 點擊修改按鈕後,為了增強用戶體驗,添加一個數據回顯功能 selectBrandById(id){ this.dialogVisibleUpdate = true // 發送ajax請求 axios.get("brand/selectBrandById?id=" + id).then(response => { // 接收後端返回的json數據 this.brand = response.data; // el-switch開關的預設值必須類型也要匹配~ this.brand.status = this.brand.status.toString(); console.log(this.brand); }); }, // 執行修改語句 update(){ // 發送ajax請求 axios.post("brand/update", this.brand).then(response => { if (response.data == "ok") { // 跳轉到brand.html頁面 window.location.href = "brand.html"; }else { window.alert("修改失敗!") } }); }, // 批量刪除數據 deleteBatch() { this.$confirm("確定要刪除嗎?","提示", { confirmButtonText: "確定", cancelButtonText: "取消", type: "warning" }).then( () => { // 點擊確定按鈕後要執行的操作 // this.$message({ // message: "刪除成功!", // type: "success" // }); let ids = []; for (let i = 0; i < this.multipleSelection.length; i++) { // ids[i] = this.multipleSelection[i].id; ids.push(this.multipleSelection[i].id); } console.log(ids); axios.post("brand/deleteByIds", ids).then( response => { if (response.data == "ok") { window.location.href = "brand.html"; } else { this.$message({ message: "刪除失敗!", type: "error" }); } }); }); }, //分頁 handleSizeChange(val) { console.log(`每頁 ${val} 條`); this.pageSize = val; this.selectAll(); }, handleCurrentChange(val) { console.log(`當前頁: ${val}`); this.currentPage = val; this.selectAll(); }, } }) </script> </body> </html>