日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

Vue高級使用,綜合案例學(xué)生管理系統(tǒng)實現(xiàn)

 小世界的野孩子 2021-04-28

課堂講義

1、Vue 高級使用

1.1、自定義組件

  • 學(xué)完了 Element 組件后,我們會發(fā)現(xiàn)組件其實就是自定義的標(biāo)簽。例如<el-button>就是對<button>的封裝

  • 本質(zhì)上,組件是帶有一個名字且可復(fù)用的 Vue 實例,我們完全可以自己定義

  • 定義格式

    Vue.component(組件名稱, {
    props:組件的屬性,
    data: 組件的數(shù)據(jù)函數(shù),
    template: 組件解析的標(biāo)簽?zāi)0?br>})
  • 代碼實現(xiàn)

    <!DOCTYPE html>
    <html lang="en">
    <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <title>自定義組件</title>
       <script src="vue/vue.js"></script>
    </head>
    <body>
       <div id="div">
           <my-button></my-button>
       </div>
    </body>
    <script>
       Vue.component("my-button",{
           // 屬性
           props:["style"],
           // 數(shù)據(jù)函數(shù)
           data: function(){
               return{
                   msg:"我的按鈕"
              }
          },
           //解析標(biāo)簽?zāi)0?br>        template:"<button style='color:red'>{{msg}}</button>"
      });
    ?
       new Vue({
           el:"#div"
      });
    </script>
    </html>

1.2、Vue的生命周期

  • 生命周期

 

 

 

  • 生命周期的八個階段

     

     

  • 代碼實現(xiàn)

    <!DOCTYPE html>
    <html lang="en">
    <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <title>生命周期</title>
       <script src="vue/vue.js"></script>
    </head>
    <body>
       <div id="app">
          {{message}}
       </div>
    </body>
    <script>
       let vm = new Vue({
    el: '#app',
    data: {
    message: 'Vue的生命周期'
    },
    beforeCreate: function() {
    console.group('------beforeCreate創(chuàng)建前狀態(tài)------');
    console.log("%c%s", "color:red", "el     : " + this.$el); //undefined
    console.log("%c%s", "color:red", "data   : " + this.$data); //undefined
    console.log("%c%s", "color:red", "message: " + this.message);//undefined
    },
    created: function() {
    console.group('------created創(chuàng)建完畢狀態(tài)------');
    console.log("%c%s", "color:red", "el     : " + this.$el); //undefined
    console.log("%c%s", "color:red", "data   : " + this.$data); //已被初始化
    console.log("%c%s", "color:red", "message: " + this.message); //已被初始化
    },
    beforeMount: function() {
    console.group('------beforeMount掛載前狀態(tài)------');
    console.log("%c%s", "color:red", "el     : " + (this.$el)); //已被初始化
    console.log(this.$el);
    console.log("%c%s", "color:red", "data   : " + this.$data); //已被初始化  
    console.log("%c%s", "color:red", "message: " + this.message); //已被初始化  
    },
    mounted: function() {
    console.group('------mounted 掛載結(jié)束狀態(tài)------');
    console.log("%c%s", "color:red", "el     : " + this.$el); //已被初始化
    console.log(this.$el);
    console.log("%c%s", "color:red", "data   : " + this.$data); //已被初始化
    console.log("%c%s", "color:red", "message: " + this.message); //已被初始化
    },
    beforeUpdate: function() {
    console.group('beforeUpdate 更新前狀態(tài)===============》');
    let dom = document.getElementById("app").innerHTML;
    console.log(dom);
    console.log("%c%s", "color:red", "el     : " + this.$el);
    console.log(this.$el);
    console.log("%c%s", "color:red", "data   : " + this.$data);
    console.log("%c%s", "color:red", "message: " + this.message);
    },
    updated: function() {
    console.group('updated 更新完成狀態(tài)===============》');
    let dom = document.getElementById("app").innerHTML;
    console.log(dom);
    console.log("%c%s", "color:red", "el     : " + this.$el);
    console.log(this.$el);
    console.log("%c%s", "color:red", "data   : " + this.$data);
    console.log("%c%s", "color:red", "message: " + this.message);
    },
    beforeDestroy: function() {
    console.group('beforeDestroy 銷毀前狀態(tài)===============》');
    console.log("%c%s", "color:red", "el     : " + this.$el);
    console.log(this.$el);
    console.log("%c%s", "color:red", "data   : " + this.$data);
    console.log("%c%s", "color:red", "message: " + this.message);
    },
    destroyed: function() {
    console.group('destroyed 銷毀完成狀態(tài)===============》');
    console.log("%c%s", "color:red", "el     : " + this.$el);
    console.log(this.$el);
    console.log("%c%s", "color:red", "data   : " + this.$data);
    console.log("%c%s", "color:red", "message: " + this.message);
    }
    });
    ?

    // 銷毀Vue對象
    //vm.$destroy();
    //vm.message = "hehe"; // 銷毀后 Vue 實例會解綁所有內(nèi)容
    ?
    // 設(shè)置data中message數(shù)據(jù)值
    vm.message = "good...";
    </script>
    </html>

1.3、Vue異步操作***

  • 在Vue中發(fā)送異步請求,本質(zhì)上還是AJAX。我們可以使用axios這個插件來簡化操作!

  • 使用步驟 1.引入axios核心js文件。 2.調(diào)用axios對象的方法來發(fā)起異步請求。 3.調(diào)用axios對象的方法來處理響應(yīng)的數(shù)據(jù)。

  • axios常用方法

     

     

  • 代碼實現(xiàn)

    • html代碼

    <!DOCTYPE html>
    <html lang="en">
    <head>
       <meta charset="UTF-8">
       <title>異步操作</title>
       <script src="js/vue.js"></script>
       <script src="js/axios-0.18.0.js"></script>
    </head>
    <body>
       <div id="div">
          {{name}}
           <button @click="send()">發(fā)起請求</button>
       </div>
    </body>
    <script>
       new Vue({
           el:"#div",
           data:{
               name:"張三"
          },
           methods:{
               send(){
                   // GET方式請求
                   // axios.get("testServlet?name=" + this.name)
                   //     .then(resp => {
                   //         alert(resp.data);
                   //     })
                   //     .catch(error => {
                   //         alert(error);
                   //     })
    ?
                   // POST方式請求
                   axios.post("testServlet","name="+this.name)
                      .then(resp => {
                           alert(resp.data);
                      })
                      .catch(error => {
                           alert(error);
                      })
              }
          }
      });
    </script>
    </html>
    • java代碼

    package com.itheima;
    ?
    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("/testServlet")
    public class TestServlet extends HttpServlet {
       @Override
       protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
           //設(shè)置請求和響應(yīng)的編碼
           req.setCharacterEncoding("UTF-8");
           resp.setContentType("text/html;charset=UTF-8");
    ?
           //獲取請求參數(shù)
           String name = req.getParameter("name");
           System.out.println(name);
    ?
           //響應(yīng)客戶端
           resp.getWriter().write("請求成功");
      }
    ?
       @Override
       protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
           this.doGet(req,resp);
      }
    }

1.4、小結(jié)

  • 自定義組件:本質(zhì)上,組件是帶有一個名字且可復(fù)用的 Vue 實例,我們可以自己來定義。

    Vue.component(組件名稱, {
    props:組件的屬性,
    data: 組件的數(shù)據(jù)函數(shù),
    template: 組件解析的標(biāo)簽?zāi)0?br>})
  • 生命周期:核心八個階段 beforeCreate:創(chuàng)建前 created:創(chuàng)建后 beforeMount:載入前 mounted:載入后 beforeUpdate:更新前 updated:更新后 beforeDestroy:銷毀前 destroyed:銷毀后

  • 異步操作:通過 axios 插件來實現(xiàn)。

     

     

2、綜合案例 學(xué)生管理系統(tǒng)***

2.1、效果環(huán)境的介紹

 

 

 

 

2.2、登錄功能的實現(xiàn)

  • 環(huán)境搭建

    • 從當(dāng)天的資料中解壓《學(xué)生管理系統(tǒng)原始項目》,并導(dǎo)入。

  • 代碼實現(xiàn)

    • html代碼

      onSubmit(formName) {
                     // 為表單綁定驗證功能
                     this.$refs[formName].validate((valid) => {
                         if (valid) {
                             //請求服務(wù)器完成登錄功能
                             axios.post("userServlet","username=" + this.form.username + "&password=" + this.form.password)
                                .then(resp => {
                                     if(resp.data == true) {
                                         //登錄成功,跳轉(zhuǎn)到首頁
                                         location.href = "index.html";
                                    }else {
                                         //登錄失敗,跳轉(zhuǎn)到登錄頁面
                                         alert("登錄失敗,請檢查用戶名和密碼");
                                         location.href = "login.html";
                                    }
                                })
                        } else {
                             return false;
                        }
                    });
                }
    • java代碼

      • UserServlet.java

      package com.itheima.controller;
      ?
      import com.itheima.bean.User;
      import com.itheima.service.UserService;
      import com.itheima.service.impl.UserServiceImpl;
      ?
      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("/userServlet")
      public class UserServlet extends HttpServlet {
         private UserService service = new UserServiceImpl();
         @Override
         protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
             //設(shè)置請求和響應(yīng)編碼
             req.setCharacterEncoding("UTF-8");
             resp.setContentType("text/html;charset=UTF-8");
      ?
             //1.獲取請求參數(shù)
             String username = req.getParameter("username");
             String password = req.getParameter("password");
      ?
             //2.封裝User對象
             User user = new User(username,password);
      ?
             //3.調(diào)用業(yè)務(wù)層的登錄方法
             List<User> list = service.login(user);
      ?
             //4.判斷是否查詢出結(jié)果
             if(list.size() != 0) {
                 //將用戶名存入會話域當(dāng)中
                 req.getSession().setAttribute("username",username);
                 //響應(yīng)給客戶端true
                 resp.getWriter().write("true");
            }else {
                 //響應(yīng)給客戶端false
                 resp.getWriter().write("false");
            }
        }
      ?
         @Override
         protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
             doGet(req,resp);
        }
      }
      • UserService.java

      package com.itheima.service;
      ?
      import com.itheima.bean.User;
      ?
      import java.util.List;
      /*
         業(yè)務(wù)層約束接口
      */
      public interface UserService {
         /*
             登錄方法
          */
         public abstract List<User> login(User user);
      }
      • UserServiceImpl.java

      package com.itheima.service.impl;
      ?
      import com.itheima.bean.User;
      import com.itheima.mapper.UserMapper;
      import com.itheima.service.UserService;
      import org.apache.ibatis.io.Resources;
      import org.apache.ibatis.session.SqlSession;
      import org.apache.ibatis.session.SqlSessionFactory;
      import org.apache.ibatis.session.SqlSessionFactoryBuilder;
      ?
      import java.io.IOException;
      import java.io.InputStream;
      import java.util.List;
      ?
      public class UserServiceImpl implements UserService {
         @Override
         public List<User> login(User user) {
             InputStream is = null;
             SqlSession sqlSession = null;
             List<User> list = null;
             try{
                 //1.加載核心配置文件
                 is = Resources.getResourceAsStream("MyBatisConfig.xml");
      ?
                 //2.獲取SqlSession工廠對象
                 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
      ?
                 //3.通過SqlSession工廠對象獲取SqlSession對象
                 sqlSession = sqlSessionFactory.openSession(true);
      ?
                 //4.獲取UserMapper接口的實現(xiàn)類對象
                 UserMapper mapper = sqlSession.getMapper(UserMapper.class);
      ?
                 //5.調(diào)用實現(xiàn)類對象的登錄方法
                 list = mapper.login(user);
      ?
            }catch (Exception e) {
                 e.printStackTrace();
            } finally {
                 //6.釋放資源
                 if(sqlSession != null) {
                     sqlSession.close();
                }
                 if(is != null) {
                     try {
                         is.close();
                    } catch (IOException e) {
                         e.printStackTrace();
                    }
                }
            }
             //7.返回結(jié)果到控制層
             return list;
        }
      }
      • UserMapper.java

      package com.itheima.mapper;
      ?
      import com.itheima.bean.User;
      import org.apache.ibatis.annotations.Select;
      ?
      import java.util.List;
      ?
      public interface UserMapper {
         /*
             登錄方法
          */
         @Select("SELECT * FROM user WHERE username=#{username} AND password=#{password}")
         public abstract List<User> login(User user);
      }

2.3、分頁查詢功能的實現(xiàn)

 

 

  • 代碼實現(xiàn)

    • html代碼

      <script>
         new Vue({
             el:"#div",
             data:{
                 dialogTableVisible4add: false,  //添加窗口顯示狀態(tài)
                 dialogTableVisible4edit: false, //編輯窗口顯示狀態(tài)
                 formData:{},//添加表單的數(shù)據(jù)
                 editFormData: {},//編輯表單的數(shù)據(jù)
                 tableData:[],//表格數(shù)據(jù)
                 pagination: {
                     currentPage: 1, //當(dāng)前頁
                     pageSize: 5,    //每頁顯示條數(shù)
                     total: 0        //總條數(shù)
                },
                 rules: {
                     number: [
                        {required: true, message: '請輸入學(xué)號', trigger: 'blur'},
                        {min: 2, max: 10, message: '長度在 2 到 10 個字符', trigger: 'blur'}
                    ],
                     name: [
                        {required: true, message: '請輸入姓名', trigger: 'blur'},
                        {min: 2, max: 10, message: '長度在 2 到 10 個字符', trigger: 'blur'}
                    ],
                     birthday: [
                        {required: true, message: '請選擇日期', trigger: 'change'}
                    ],
                     address: [
                        {required: true, message: '請輸入地址', trigger: 'blur'},
                        {min: 2, max: 200, message: '長度在 2 到 200 個字符', trigger: 'blur'}
                    ],
                }
            },
             methods:{
                 //分頁查詢功能
                 selectByPage(){
                     axios.post("studentServlet","method=selectByPage&currentPage=" + this.pagination.currentPage + "&pageSize=" + this.pagination.pageSize)
                        .then(resp => {
                             //將查詢出的數(shù)據(jù)賦值tableData
                             this.tableData = resp.data.list;
                             //設(shè)置分頁參數(shù)
                             //當(dāng)前頁
                             this.pagination.currentPage = resp.data.pageNum;
                             //總條數(shù)
                             this.pagination.total = resp.data.total;
                        })
                },
                 //改變每頁條數(shù)時執(zhí)行的函數(shù)
                 handleSizeChange(pageSize) {
                     //修改分頁查詢的參數(shù)
                     this.pagination.pageSize = pageSize;
                     //重新執(zhí)行查詢
                     this.selectByPage();
                },
                 //改變頁碼時執(zhí)行的函數(shù)
                 handleCurrentChange(pageNum) {
                     //修改分頁查詢的參數(shù)
                     this.pagination.currentPage = pageNum;
                     //重新執(zhí)行查詢
                     this.selectByPage();
                },
                 showAddStu() {
                     //彈出窗口
                     this.dialogTableVisible4add = true;
                },
                 resetForm(addForm) {
                     //雙向綁定,輸入的數(shù)據(jù)都賦值給了formData, 清空formData數(shù)據(jù)
                     this.formData = {};
                     //清除表單的校驗數(shù)據(jù)
                     this.$refs[addForm].resetFields();
                },
                 showEditStu(row) {
                     //1. 彈出窗口
                     this.dialogTableVisible4edit = true;
      ?
                     //2. 顯示表單數(shù)據(jù)
                     this.editFormData = {
                         number:row.number,
                         name:row.name,
                         birthday:row.birthday,
                         address:row.address,
                    }
                }  
            },
             mounted(){
                 //調(diào)用分頁查詢功能
                 this.selectByPage();
            }
        });
      </script>
    • java代碼

      • 1、創(chuàng)建StudentServlet.java

      package com.itheima.controller;
      ?
      import com.fasterxml.jackson.databind.ObjectMapper;
      import com.github.pagehelper.Page;
      import com.github.pagehelper.PageInfo;
      import com.itheima.bean.Student;
      import com.itheima.service.StudentService;
      import com.itheima.service.impl.StudentServiceImpl;
      import org.apache.commons.beanutils.BeanUtils;
      import org.apache.commons.beanutils.ConvertUtils;
      import org.apache.commons.beanutils.Converter;
      ?
      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.text.ParseException;
      import java.text.SimpleDateFormat;
      import java.util.Date;
      import java.util.Map;
      ?
      @WebServlet("/studentServlet")
      public class StudentServlet extends HttpServlet {
         private StudentService service = new StudentServiceImpl();
         @Override
         protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
             //設(shè)置請求和響應(yīng)編碼
             req.setCharacterEncoding("UTF-8");
             resp.setContentType("text/html;charset=UTF-8");
      ?
             //1.獲取方法名
             String method = req.getParameter("method");
             if(method.equals("selectByPage")) {
                 //分頁查詢功能
                 selectByPage(req,resp);
            }
        }
      ?
         /*
             分頁查詢功能
          */
         private void selectByPage(HttpServletRequest req, HttpServletResponse resp) {
             //獲取請求參數(shù)
             String currentPage = req.getParameter("currentPage");
             String pageSize = req.getParameter("pageSize");
      ?
             //調(diào)用業(yè)務(wù)層的查詢方法
             Page page = service.selectByPage(Integer.parseInt(currentPage), Integer.parseInt(pageSize));
      ?
             //封裝PageInfo
             PageInfo info = new PageInfo(page);
      ?
             //將info轉(zhuǎn)成json,響應(yīng)給客戶端
             try {
                 String json = new ObjectMapper().writeValueAsString(info);
                 resp.getWriter().write(json);
            } catch (Exception e) {
                 e.printStackTrace();
            }
        }
      ?
         @Override
         protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
             doGet(req,resp);
        }
      }
      • 2、創(chuàng)建StudentService.java

      package com.itheima.service;
      ?
      import com.github.pagehelper.Page;
      import com.itheima.bean.Student;
      ?
      /*
         學(xué)生業(yè)務(wù)層接口
      */
      public interface StudentService {
         /*
             分頁查詢方法
          */
         public abstract Page selectByPage(Integer currentPage, Integer pageSize);
      }
      • 3、創(chuàng)建StudentServiceImpl.java

      package com.itheima.service.impl;
      ?
      import com.github.pagehelper.Page;
      import com.github.pagehelper.PageHelper;
      import com.itheima.bean.Student;
      import com.itheima.mapper.StudentMapper;
      import com.itheima.service.StudentService;
      import org.apache.ibatis.io.Resources;
      import org.apache.ibatis.session.SqlSession;
      import org.apache.ibatis.session.SqlSessionFactory;
      import org.apache.ibatis.session.SqlSessionFactoryBuilder;
      ?
      import java.io.IOException;
      import java.io.InputStream;
      ?
      /*
         學(xué)生業(yè)務(wù)層實現(xiàn)類
      */
      public class StudentServiceImpl implements StudentService {
      ?
         /*
             分頁查詢功能
          */
         @Override
         public Page selectByPage(Integer currentPage, Integer pageSize) {
             InputStream is = null;
             SqlSession sqlSession = null;
             Page page = null;
             try{
                 //1.加載核心配置文件
                 is = Resources.getResourceAsStream("MyBatisConfig.xml");
                 //2.獲取SqlSession工廠對象
                 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
                 //3.通過SqlSession工廠對象獲取SqlSession對象
                 sqlSession = sqlSessionFactory.openSession(true);
                 //4.獲取StudentMapper接口實現(xiàn)類對象
                 StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
                 //5.設(shè)置分頁參數(shù)
                 page = PageHelper.startPage(currentPage,pageSize);
                 //6.調(diào)用實現(xiàn)類對象查詢?nèi)糠椒?br>            mapper.selectAll();
            } catch (Exception e) {
                 e.printStackTrace();
            } finally {
                 //7.釋放資源
                 if(sqlSession != null) {
                     sqlSession.close();
                }
                 if(is != null) {
                     try {
                         is.close();
                    } catch (IOException e) {
                         e.printStackTrace();
                    }
                }
            }
      ?
             //8.返回結(jié)果到控制層
             return page;
        }
      }
      • 4、創(chuàng)建StudentMapper.java

      package com.itheima.mapper;
      ?
      import com.itheima.bean.Student;
      import org.apache.ibatis.annotations.Delete;
      import org.apache.ibatis.annotations.Insert;
      import org.apache.ibatis.annotations.Select;
      import org.apache.ibatis.annotations.Update;
      ?
      import java.util.List;
      ?
      /*
         學(xué)生持久層接口
      */
      public interface StudentMapper {
         /*
             查詢?nèi)糠椒?br>     */
         @Select("SELECT * FROM student")
         public abstract List<Student> selectAll();
      }
      ?

2.4、添加功能的實現(xiàn)

 

 

  • 代碼實現(xiàn)

    • html代碼

      在stuList.html中增加“添加功能”代碼

      //添加學(xué)生功能
                  addStu(){
                      let param = "method=addStu&number=" + this.formData.number + "&name=" + this.formData.name +
                              "&birthday=" + this.formData.birthday + "&address=" + this.formData.address +
                              "&currentPage=" + this.pagination.currentPage + "&pageSize=" + this.pagination.pageSize;
                      axios.post("studentServlet",param)
                          .then(resp => {
                              //將查詢出的數(shù)據(jù)賦值tableData
                              this.tableData = resp.data.list;
                              //設(shè)置分頁參數(shù)
                              //當(dāng)前頁
                              this.pagination.currentPage = resp.data.pageNum;
                              //總條數(shù)
                              this.pagination.total = resp.data.total;
                          })
                      //關(guān)閉添加窗口
                      this.dialogTableVisible4add = false;
                  }
    • java代碼

      • 1、在StudentServlet.java中增加“添加功能”代碼-addStu

      /*
      *1、直接復(fù)制會報錯
      *2、需要將此行代碼需要添加到“doGet”方法中
      *3、增加“addStu”方法名的判斷
          */
      else if(method.equals("addStu")) {
                  //添加數(shù)據(jù)功能
                  addStu(req,resp);
           }
      ==================================================================================
      
      /*
              添加數(shù)據(jù)功能
           */
          private void addStu(HttpServletRequest req, HttpServletResponse resp) {
              //獲取請求參數(shù)
              Map<String, String[]> map = req.getParameterMap();
              String currentPage = req.getParameter("currentPage");
              String pageSize = req.getParameter("pageSize");
      
              //封裝Student對象
              Student stu = new Student();
      
              //注冊日期轉(zhuǎn)換器方法
              dateConvert();
      
              try {
                  BeanUtils.populate(stu,map);
              } catch (Exception e) {
                  e.printStackTrace();
              }
      
              //調(diào)用業(yè)務(wù)層的添加方法
              service.addStu(stu);
      
              //重定向到分頁查詢功能
              try {
                  resp.sendRedirect(req.getContextPath() + "/studentServlet?method=selectByPage&currentPage=" + currentPage + "&pageSize=" + pageSize);
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      
          /*
              日期轉(zhuǎn)換
           */
          private void dateConvert() {
              ConvertUtils.register(new Converter() {
                  public Object convert(Class type, Object value) {
                      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                      try {
                          return simpleDateFormat.parse(value.toString());
                      } catch (ParseException e) {
                          e.printStackTrace();
                      }
                      return null;
                  }
              }, Date.class);
          }
      • 2、在StudentService.java中增加“添加功能”-addStu

          /*
              添加數(shù)據(jù)方法
           */
          public abstract void addStu(Student stu);
      • 3、StudentServiceImpl.java中增加“添加功能”-addStu

      /*
             添加數(shù)據(jù)方法
          */
         @Override
         public void addStu(Student stu) {
             InputStream is = null;
             SqlSession sqlSession = null;
             try{
                 //1.加載核心配置文件
                 is = Resources.getResourceAsStream("MyBatisConfig.xml");
                 //2.獲取SqlSession工廠對象
                 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
                 //3.通過SqlSession工廠對象獲取SqlSession對象
                 sqlSession = sqlSessionFactory.openSession(true);
                 //4.獲取StudentMapper接口實現(xiàn)類對象
                 StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
                 //5.調(diào)用實現(xiàn)類對象添加方法
                 mapper.addStu(stu);
            } catch (Exception e) {
                 e.printStackTrace();
            } finally {
                 //6.釋放資源
                 if(sqlSession != null) {
                     sqlSession.close();
                }
                 if(is != null) {
                     try {
                         is.close();
                    } catch (IOException e) {
                         e.printStackTrace();
                    }
                }
            }
        }
      • 4、StudentMapper.java中增加“添加功能”-addStu

          /*
             添加數(shù)據(jù)方法
          */
         @Insert("INSERT INTO student VALUES (#{number},#{name},#{birthday},#{address})")
         public abstract void addStu(Student stu);

2.5、修改功能的實現(xiàn)

 

 

  • 代碼實現(xiàn)

    • html代碼

      在stuList.html中增加“修改功能”代碼

      //修改數(shù)據(jù)功能
                 updateStu() {
                     let param = "method=updateStu&number=" + this.editFormData.number + "&name=" + this.editFormData.name +
                         "&birthday=" + this.editFormData.birthday + "&address=" + this.editFormData.address +
                         "&currentPage=" + this.pagination.currentPage + "&pageSize=" + this.pagination.pageSize;
                     axios.post("studentServlet",param)
                        .then(resp => {
                             //將查詢出的數(shù)據(jù)賦值tableData
                             this.tableData = resp.data.list;
                             //設(shè)置分頁參數(shù)
                             //當(dāng)前頁
                             this.pagination.currentPage = resp.data.pageNum;
                             //總條數(shù)
                             this.pagination.total = resp.data.total;
                        })
                     //關(guān)閉編輯窗口
                     this.dialogTableVisible4edit = false;
                }
    • java代碼

      • 1、在StudentServlet.java中增加“修改功能”-updateStu

          /*
              修改數(shù)據(jù)功能
           */
          private void updateStu(HttpServletRequest req, HttpServletResponse resp) {
              //獲取請求參數(shù)
              Map<String, String[]> map = req.getParameterMap();
              String currentPage = req.getParameter("currentPage");
              String pageSize = req.getParameter("pageSize");
      
              //封裝Student對象
              Student stu = new Student();
      
              //注冊日期轉(zhuǎn)換器方法
              dateConvert();
      
              try {
                  BeanUtils.populate(stu,map);
              } catch (Exception e) {
                  e.printStackTrace();
              }
      
              //調(diào)用業(yè)務(wù)層的修改方法
              service.updateStu(stu);
      
              //重定向到分頁查詢功能
              try {
                  resp.sendRedirect(req.getContextPath() + "/studentServlet?method=selectByPage&currentPage=" + currentPage + "&pageSize=" + pageSize);
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      • 2、在StudentService.java中增加“修改功能”-updateStu

      /*
              修改數(shù)據(jù)方法
           */
          public abstract void updateStu(Student stu);
      • 3、StudentServiceImpl.java中增加“修改功能”-updateStu

      /*
      *1、直接復(fù)制會報錯
      *2、需要將此行代碼需要添加到“doGet”方法中
      *3、增加“updateStu”方法名的判斷
          */
      else if(method.equals("updateStu")) {
                  //添加數(shù)據(jù)功能
                  updateStu(req,resp);
           }
      ==================================================================================
      
      /*
              修改數(shù)據(jù)方法
           */
          @Override
          public void updateStu(Student stu) {
              InputStream is = null;
              SqlSession sqlSession = null;
              try{
                  //1.加載核心配置文件
                  is = Resources.getResourceAsStream("MyBatisConfig.xml");
                  //2.獲取SqlSession工廠對象
                  SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
                  //3.通過SqlSession工廠對象獲取SqlSession對象
                  sqlSession = sqlSessionFactory.openSession(true);
                  //4.獲取StudentMapper接口實現(xiàn)類對象
                  StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
                  //5.調(diào)用實現(xiàn)類對象修改方法
                  mapper.updateStu(stu);
              } catch (Exception e) {
                  e.printStackTrace();
              } finally {
                  //6.釋放資源
                  if(sqlSession != null) {
                      sqlSession.close();
                  }
                  if(is != null) {
                      try {
                          is.close();
                      } catch (IOException e) {
                          e.printStackTrace();
                      }
                  }
              }
          }
      • 4、StudentMapper.java中增加“修改功能”-updateStu

      /*
              修改數(shù)據(jù)方法
           */
          @Update("UPDATE student SET number=#{number},name=#{name},birthday=#{birthday},address=#{address} WHERE number=#{number}")
          public abstract void updateStu(Student stu);

2.6、刪除功能的實現(xiàn)

  • 代碼實現(xiàn)

    • html代碼

      在stuList.html中增加“刪除功能”代碼

      //刪除數(shù)據(jù)功能
                  deleteStu(row) {
                      if(confirm("確定要刪除" + row.number + "數(shù)據(jù)?")) {
                          let param = "method=deleteStu&number=" + row.number +
                              "&currentPage=" + this.pagination.currentPage + "&pageSize=" + this.pagination.pageSize;
                          axios.post("studentServlet",param)
                              .then(resp => {
                                  //將查詢出的數(shù)據(jù)賦值tableData
                                  this.tableData = resp.data.list;
                                  //設(shè)置分頁參數(shù)
                                  //當(dāng)前頁
                                  this.pagination.currentPage = resp.data.pageNum;
                                  //總條數(shù)
                                  this.pagination.total = resp.data.total;
                              })
                      }
                  }
    • java代碼

      • 1、在StudentServlet.java中增加“刪除功能”-

          /*
      *1、直接復(fù)制會報錯
      *2、需要將此行代碼需要添加到“doGet”方法中
      *3、增加“deleteStu”方法名的判斷
         */
      else if(method.equals("deleteStu")) {
                 //添加數(shù)據(jù)功能
                 deleteStu(req,resp);
          }
      ==================================================================================
      ?
      ?
      /*
             刪除數(shù)據(jù)功能
          */
         private void deleteStu(HttpServletRequest req, HttpServletResponse resp) {
             //獲取請求參數(shù)
             String number = req.getParameter("number");
             String currentPage = req.getParameter("currentPage");
             String pageSize = req.getParameter("pageSize");
      ?
             //調(diào)用業(yè)務(wù)層的刪除方法
             service.deleteStu(number);
      ?
             //重定向到分頁查詢功能
             try {
                 resp.sendRedirect(req.getContextPath() + "/studentServlet?method=selectByPage&currentPage=" + currentPage + "&pageSize=" + pageSize);
            } catch (IOException e) {
                 e.printStackTrace();
            }
        }
      • 2、在StudentService.java中增加“刪除功能”-

          /*
              刪除數(shù)據(jù)方法
           */
          public abstract void deleteStu(String number);
      • 3、StudentServiceImpl.java中增加“刪除功能”-

      /*
             刪除數(shù)據(jù)方法
          */
         @Override
         public void deleteStu(String number) {
             InputStream is = null;
             SqlSession sqlSession = null;
             try{
                 //1.加載核心配置文件
                 is = Resources.getResourceAsStream("MyBatisConfig.xml");
                 //2.獲取SqlSession工廠對象
                 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
                 //3.通過SqlSession工廠對象獲取SqlSession對象
                 sqlSession = sqlSessionFactory.openSession(true);
                 //4.獲取StudentMapper接口實現(xiàn)類對象
                 StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
                 //5.調(diào)用實現(xiàn)類對象刪除方法
                 mapper.deleteStu(number);
            } catch (Exception e) {
                 e.printStackTrace();
            } finally {
                 //6.釋放資源
                 if(sqlSession != null) {
                     sqlSession.close();
                }
                 if(is != null) {
                     try {
                         is.close();
                    } catch (IOException e) {
                         e.printStackTrace();
                    }
                }
            }
        }
      • 4、StudentMapper.java中增加“刪除功能”-

          /*
             刪除數(shù)據(jù)方法
          */
         @Delete("DELETE FROM student WHERE number=#{number}")
         public abstract void deleteStu(String number);

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多