主頁 > 後端開發 > 12-基于ElementUI&Servlet的CRUD綜合案例

12-基于ElementUI&Servlet的CRUD綜合案例

2022-08-04 07:44:55 後端開發

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、思路

  • 當發送請求至servlettomcat會自動呼叫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");
          }
      
      }
      
注意事項
  • BaseServletBrandServlet要放在同一個包下,否則因為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

下一篇:IOS OpenGL ES GPUImage 影像透明混合 GPUImageAlphaBlendFilter

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more