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="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/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 = https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/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 =https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/="ok") { this.dialogVisible = false; window.location.href = "https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/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 =https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/="ok") { // 洗掉成功,跳轉回brand.html window.location.href = "https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/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 =https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/="ok") { // 跳轉到brand.html頁面 window.location.href = "https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/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 =https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/="ok") { window.location.href = "https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/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 = https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/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 = https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/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 = https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/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" > <el-form-item label="當前狀態"> <el-select v-model="brand.status" placeholder="當前狀態"> <el-option label="啟用" value="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/1"></el-option> <el-option label="禁用" value="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/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" > <el-form ref="form" :model="brand" label-> <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="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/1" inactive-value="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/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" > <el-form ref="form" :model="brand" label-> <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="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/1" inactive-value="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/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="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/tableData" style="width: 100%" :row-class-name="tableRowClassName" @selection-change="handleSelectionChange" > <el-table-column type="selection" > </el-table-column> <el-table-column type="index" > </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="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/js/vue.js"></script> <script src="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/js/axios-0.18.0.js"></script> <script src="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/element-ui/lib/index.js"></script> <link rel="stylesheet" href="https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/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 = https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/response.data.list; }); }, // 添加資料 addBrand(){ console.log(this.brand); axios.post("brand/add", this.brand).then(response => { if (response.data =https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/="ok") { this.dialogVisible = false; window.location.href = "https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/brand.html"; } else { window.alert("添加失敗!"); } }) }, // 洗掉資料 deleteBrandById(id){ // 發送ajax請求 axios.get("brand/delete?id=" + id).then( response => { if (response.data =https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/="ok") { // 洗掉成功,跳轉回brand.html window.location.href = "https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/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 =https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/="ok") { // 跳轉到brand.html頁面 window.location.href = "https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/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 =https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/="ok") { window.location.href = "https://www.cnblogs.com/OnlyOnYourself-lzw/archive/2022/08/03/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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/500755.html
標籤:其他
上一篇:Javaweb02-jsp


