JAVA - Vue and comprehensive case

Keywords: Java Database MySQL Vue

1. Vue advanced usage

1.1. Custom components

  • After learning the Element component, we will find that the component is actually a custom label. For example, the encapsulation of.

  • In essence, a component is a reusable Vue instance with a name, which can be defined by ourselves.

  • Define format

    Vue.component(Component name, {
     props:Properties of the component,
     data: Component data function,
     template: Label template resolved by component
    })
    
  • code implementation

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Custom components</title>
        <script src="vue/vue.js"></script>
    </head>
    <body>
        <div id="div">
            <my-button>My button</my-button>
        </div>
    </body>
    <script>
        Vue.component("my-button",{
            // attribute
            props:["style"],
            // Data function
            data: function(){
                return{
                    msg:"My button"
                }
            },
            //Parsing label templates
            template:"<button style='color:red'>{{msg}}</button>"
        });
    
        new Vue({
            el:"#div"
        });
    </script>
    </html>
    

1.2 life cycle of Vue

  • life cycle

  • Eight stages of the life cycle

  • code implementation

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>life cycle</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 Life cycle of'
    				},
    				beforeCreate: function() {
    					console.group('------beforeCreate Pre creation status------');
    					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 Create complete status------');
    					console.log("%c%s", "color:red", "el     : " + this.$el); //undefined
    					console.log("%c%s", "color:red", "data   : " + this.$data); //Has been initialized 
    					console.log("%c%s", "color:red", "message: " + this.message); //Has been initialized
    				},
    				beforeMount: function() {
    					console.group('------beforeMount Pre mount status------');
    					console.log("%c%s", "color:red", "el     : " + (this.$el)); //Has been initialized
    					console.log(this.$el);
    					console.log("%c%s", "color:red", "data   : " + this.$data); //Has been initialized  
    					console.log("%c%s", "color:red", "message: " + this.message); //Has been initialized  
    				},
    				mounted: function() {
    					console.group('------mounted Mount end status------');
    					console.log("%c%s", "color:red", "el     : " + this.$el); //Has been initialized
    					console.log(this.$el);
    					console.log("%c%s", "color:red", "data   : " + this.$data); //Has been initialized
    					console.log("%c%s", "color:red", "message: " + this.message); //Has been initialized 
    				},
    				beforeUpdate: function() {
    					console.group('beforeUpdate Status before update===============>');
    					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 Update completion status===============>');
    					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 Status before destruction===============>');
    					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 Destroy complete status===============>');
    					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);
    				}
    			});
    
    		
    			// Destroy Vue objects
    			//vm.$destroy();
    			//vm.message = "hehe"; 	//  After destruction, the Vue instance will unbind all contents
    
    			// Set message data value in data
    			vm.message = "good...";
    </script>
    </html>
    

1.3 Vue asynchronous operation

  • Sending asynchronous requests in Vue is essentially AJAX. We can use the axios plug-in to simplify the operation!

  • Use steps
    1. Introduce the core js file of axios.
    2. Call the method of axios object to initiate asynchronous request.
    3. Call the method of axios object to process the data of the response.

  • axios common methods

  • code implementation

    • html code
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Asynchronous operation</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()">Initiate request</button>
        </div>
    </body>
    <script>
        new Vue({
            el:"#div",
            data:{
                name:"Zhang San"
            },
            methods:{
                send(){
                    // GET mode request
                    // axios.get("testServlet?name=" + this.name)
                    //     .then(resp => {
                    //         alert(resp.data);
                    //     })
                    //     .catch(error => {
                    //         alert(error);
                    //     })
    
                    // POST mode request
                    axios.post("testServlet","name="+this.name)
                        .then(resp => {
                            alert(resp.data);
                        })
                        .catch(error => {
                            alert(error);
                        })
                }
            }
        });
    </script>
    </html>
    
    • java code
    package com.xxx;
    
    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 {
            //Set the encoding of the request and response
            req.setCharacterEncoding("UTF-8");
            resp.setContentType("text/html;charset=UTF-8");
    
            //Get request parameters
            String name = req.getParameter("name");
            System.out.println(name);
    
            //Response client
            resp.getWriter().write("Request succeeded");
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            this.doGet(req,resp);
        }
    }
    

1.4 summary

  • Custom component: in essence, a component is a reusable Vue instance with a name. We can define it ourselves.

    Vue.component(Component name, {
     props:Properties of the component,
     data: Component data function,
     template: Label template resolved by component
    })
    
  • Life cycle: core eight stages
    beforeCreate: before creating
    created: after creation
    beforeMount: before loading
    mounted: after loading
    beforeUpdate: before update
    Updated: updated
    beforeDestroy: Before destruction
    destroyed: after destruction

  • Asynchronous operation: implemented through the axios plug-in.

2. Comprehensive case student management system

2.1 introduction to effect environment

2.2. Realization of login function

  • Environment construction

    • Extract the original project of student management system from the materials of the day and import it.
  • code implementation

    • html code

      onSubmit(formName) {
                      // Bind validation function for form
                      this.$refs[formName].validate((valid) => {
                          if (valid) {
                              //Request the server to complete the login function
                              axios.post("userServlet","username=" + this.form.username + "&password=" + this.form.password)
                                  .then(resp => {
                                      if(resp.data == true) {
                                          //Login successful, jump to the home page
                                          location.href = "index.html";
                                      }else {
                                          //Login failed, jump to login page
                                          alert("Login failed, please check the user name and password");
                                          location.href = "login.html";
                                      }
                                  })
                          } else {
                              return false;
                          }
                      });
                  }
      
    • java code

      • UserServlet.java
      package com.xxx.controller;
      
      import com.xxx.bean.User;
      import com.xxx.service.UserService;
      import com.xxx.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 {
              //Set request and response encoding
              req.setCharacterEncoding("UTF-8");
              resp.setContentType("text/html;charset=UTF-8");
      
              //1. Get request parameters
              String username = req.getParameter("username");
              String password = req.getParameter("password");
      
              //2. Encapsulate User objects
              User user = new User(username,password);
      
              //3. Call the login method of the business layer
              List<User> list = service.login(user);
      
              //4. Judge whether the query result is found
              if(list.size() != 0) {
                  //Save the user name into the session domain
                  req.getSession().setAttribute("username",username);
                  //Respond to client true
                  resp.getWriter().write("true");
              }else {
                  //Respond to client false
                  resp.getWriter().write("false");
              }
          }
      
          @Override
          protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
              doGet(req,resp);
          }
      }
      
      • UserService.java
      package com.xxx.service;
      
      import com.xxx.bean.User;
      
      import java.util.List;
      /*
          Business layer constraint interface
       */
      public interface UserService {
          /*
              Login method
           */
          public abstract List<User> login(User user);
      }
      
      
      • UserServiceImpl.java
      package com.xxx.service.impl;
      
      import com.xxx.bean.User;
      import com.xxx.mapper.UserMapper;
      import com.xxx.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. Load the core configuration file
                  is = Resources.getResourceAsStream("MyBatisConfig.xml");
      
                  //2. Get SqlSession factory object
                  SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
      
                  //3. Obtain the SqlSession object through the SqlSession factory object
                  sqlSession = sqlSessionFactory.openSession(true);
      
                  //4. Get the implementation class object of UserMapper interface
                  UserMapper mapper = sqlSession.getMapper(UserMapper.class);
      
                  //5. Call the login method of the implementation class object
                  list = mapper.login(user);
      
              }catch (Exception e) {
                  e.printStackTrace();
              } finally {
                  //6. Release resources
                  if(sqlSession != null) {
                      sqlSession.close();
                  }
                  if(is != null) {
                      try {
                          is.close();
                      } catch (IOException e) {
                          e.printStackTrace();
                      }
                  }
              }
              //7. Return the result to the control layer
              return list;
          }
      }
      
      
      • UserMapper.java
      package com.xxx.mapper;
      
      import com.xxx.bean.User;
      import org.apache.ibatis.annotations.Select;
      
      import java.util.List;
      
      public interface UserMapper {
          /*
              Login method
           */
          @Select("SELECT * FROM user WHERE username=#{username} AND password=#{password}")
          public abstract List<User> login(User user);
      }
      
      

2.3 implementation of paging query function

  • code implementation

    • html code

      <script>
          new Vue({
              el:"#div",
              data:{
                  dialogTableVisible4add: false,  //Add window display status
                  dialogTableVisible4edit: false, //Edit window display status
                  formData:{},//Add form data
                  editFormData: {},//Edit form data
                  tableData:[],//Tabular data
                  pagination: {
                      currentPage: 1, //Current page
                      pageSize: 5,    //Number of displays per page
                      total: 0        //Total number
                  },
                  rules: {
                      number: [
                          {required: true, message: 'Please enter student number', trigger: 'blur'},
                          {min: 2, max: 10, message: 'The length is between 2 and 10 characters', trigger: 'blur'}
                      ],
                      name: [
                          {required: true, message: 'Please enter your name', trigger: 'blur'},
                          {min: 2, max: 10, message: 'The length is between 2 and 10 characters', trigger: 'blur'}
                      ],
                      birthday: [
                          {required: true, message: 'Please select a date', trigger: 'change'}
                      ],
                      address: [
                          {required: true, message: 'Please enter the address', trigger: 'blur'},
                          {min: 2, max: 200, message: 'The length is between 2 and 200 characters', trigger: 'blur'}
                      ],
                  }
              },
              methods:{
                  //Paging query function
                  selectByPage(){
                      axios.post("studentServlet","method=selectByPage&currentPage=" + this.pagination.currentPage + "&pageSize=" + this.pagination.pageSize)
                          .then(resp => {
                              //Assign the queried data to tableData
                              this.tableData = resp.data.list;
                              //Set paging parameters
                              //Current page
                              this.pagination.currentPage = resp.data.pageNum;
                              //Total number
                              this.pagination.total = resp.data.total;
                          })
                  },
                  //Function executed when changing the number of entries per page
                  handleSizeChange(pageSize) {
                      //Modify parameters of paging query
                      this.pagination.pageSize = pageSize;
                      //Re execute query
                      this.selectByPage();
                  },
                  //Function executed when changing page number
                  handleCurrentChange(pageNum) {
                      //Modify parameters of paging query
                      this.pagination.currentPage = pageNum;
                      //Re execute query
                      this.selectByPage();
                  },
                  showAddStu() {
                      //Pop up window
                      this.dialogTableVisible4add = true;
                  },
                  resetForm(addForm) {
                      //Two way binding, the input data is assigned to formData, and the formData data is cleared
                      this.formData = {};
                      //Clear the verification data of the form
                      this.$refs[addForm].resetFields();
                  },
                  showEditStu(row) {
                      //1. Pop up window
                      this.dialogTableVisible4edit = true;
      
                      //2. Display form data
                      this.editFormData = {
                          number:row.number,
                          name:row.name,
                          birthday:row.birthday,
                          address:row.address,
                      }
                  }   
              },
              mounted(){
                  //Call paging query function
                  this.selectByPage();
              }
          });
      </script>
      
      
    • java code

      • 1. Create StudentServlet.java
      package com.xxx.controller;
      
      import com.fasterxml.jackson.databind.ObjectMapper;
      import com.github.pagehelper.Page;
      import com.github.pagehelper.PageInfo;
      import com.xxx.bean.Student;
      import com.xxx.service.StudentService;
      import com.xxx.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 {
              //Set request and response encoding
              req.setCharacterEncoding("UTF-8");
              resp.setContentType("text/html;charset=UTF-8");
      
              //1. Get method name
              String method = req.getParameter("method");
              if(method.equals("selectByPage")) {
                  //Paging query function
                  selectByPage(req,resp);
              }
          }
      
          /*
              Paging query function
           */
          private void selectByPage(HttpServletRequest req, HttpServletResponse resp) {
              //Get request parameters
              String currentPage = req.getParameter("currentPage");
              String pageSize = req.getParameter("pageSize");
      
              //Call the query method of the business layer
              Page page = service.selectByPage(Integer.parseInt(currentPage), Integer.parseInt(pageSize));
      
              //Encapsulate PageInfo
              PageInfo info = new PageInfo(page);
      
              //Convert info into json and respond to the client
              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. Create StudentService.java
      package com.xxx.service;
      
      import com.github.pagehelper.Page;
      import com.xxx.bean.Student;
      
      /*
          Student business layer interface
       */
      public interface StudentService {
          /*
              Paging query method
           */
          public abstract Page selectByPage(Integer currentPage, Integer pageSize);
      }
      
      
      • 3. Create StudentServiceImpl.java
      package com.xxx.service.impl;
      
      import com.github.pagehelper.Page;
      import com.github.pagehelper.PageHelper;
      import com.xxx.bean.Student;
      import com.xxx.mapper.StudentMapper;
      import com.xxx.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;
      
      /*
          Student business layer implementation class
       */
      public class StudentServiceImpl implements StudentService {
      
          /*
              Paging query function
           */
          @Override
          public Page selectByPage(Integer currentPage, Integer pageSize) {
              InputStream is = null;
              SqlSession sqlSession = null;
              Page page = null;
              try{
                  //1. Load the core configuration file
                  is = Resources.getResourceAsStream("MyBatisConfig.xml");
                  //2. Get SqlSession factory object
                  SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
                  //3. Obtain the SqlSession object through the SqlSession factory object
                  sqlSession = sqlSessionFactory.openSession(true);
                  //4. Get the StudentMapper interface implementation class object
                  StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
                  //5. Set paging parameters
                  page = PageHelper.startPage(currentPage,pageSize);
                  //6. Call all methods of implementing class object query
                  mapper.selectAll();
              } catch (Exception e) {
                  e.printStackTrace();
              } finally {
                  //7. Release resources
                  if(sqlSession != null) {
                      sqlSession.close();
                  }
                  if(is != null) {
                      try {
                          is.close();
                      } catch (IOException e) {
                          e.printStackTrace();
                      }
                  }
              }
      
              //8. Return the result to the control layer
              return page;
          }
      }
      
      
      • 4. Create StudentMapper.java
      package com.xxx.mapper;
      
      import com.xxx.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;
      
      /*
          Student persistence layer interface
       */
      public interface StudentMapper {
          /*
              Query all methods
           */
          @Select("SELECT * FROM student")
          public abstract List<Student> selectAll();
      }
      
      
      

2.4 implementation of adding function

  • code implementation

    • html code

      Add "add function" code in stuList.html

      //Add student function
                  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 => {
                              //Assign the queried data to tableData
                              this.tableData = resp.data.list;
                              //Set paging parameters
                              //Current page
                              this.pagination.currentPage = resp.data.pageNum;
                              //Total number
                              this.pagination.total = resp.data.total;
                          })
                      //Close the add window
                      this.dialogTableVisible4add = false;
                  }
      
      
    • java code

      • 1. Add the "add function" code - addStu in StudentServlet.java
      	/*
      	*1,Direct copy will report an error
      	*2,This line of code needs to be added to the "doGet" method
      	*3,Add the judgment of "addStu" method name	
          */
      	else if(method.equals("addStu")) {
                  //Add data function
                  addStu(req,resp);
           }	
      ==================================================================================
      
      	/*
              Add data function
           */
          private void addStu(HttpServletRequest req, HttpServletResponse resp) {
              //Get request parameters
              Map<String, String[]> map = req.getParameterMap();
              String currentPage = req.getParameter("currentPage");
              String pageSize = req.getParameter("pageSize");
      
              //Encapsulating Student objects
              Student stu = new Student();
      
              //Registration date converter method
              dateConvert();
      
              try {
                  BeanUtils.populate(stu,map);
              } catch (Exception e) {
                  e.printStackTrace();
              }
      
              //Call the add method of the business layer
              service.addStu(stu);
      
              //Redirect to paging query function
              try {
                  resp.sendRedirect(req.getContextPath() + "/studentServlet?method=selectByPage&currentPage=" + currentPage + "&pageSize=" + pageSize);
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      
          /*
              Date conversion
           */
          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. Add "add function" - addStu in StudentService.java
          /*
              Add data method
           */
          public abstract void addStu(Student stu);
      
      
      • 3. Add "add function" - addStu in StudentServiceImpl.java
      /*
              Add data method
           */
          @Override
          public void addStu(Student stu) {
              InputStream is = null;
              SqlSession sqlSession = null;
              try{
                  //1. Load the core configuration file
                  is = Resources.getResourceAsStream("MyBatisConfig.xml");
                  //2. Get SqlSession factory object
                  SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
                  //3. Obtain the SqlSession object through the SqlSession factory object
                  sqlSession = sqlSessionFactory.openSession(true);
                  //4. Get the StudentMapper interface implementation class object
                  StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
                  //5. Call the implementation class object addition method
                  mapper.addStu(stu);
              } catch (Exception e) {
                  e.printStackTrace();
              } finally {
                  //6. Release resources
                  if(sqlSession != null) {
                      sqlSession.close();
                  }
                  if(is != null) {
                      try {
                          is.close();
                      } catch (IOException e) {
                          e.printStackTrace();
                      }
                  }
              }
          }
      
      
      • 4. Add "add function" - addStu in StudentMapper.java
          /*
              Add data method
           */
          @Insert("INSERT INTO student VALUES (#{number},#{name},#{birthday},#{address})")
          public abstract void addStu(Student stu);
      
      

2.5 realization of modification function

  • code implementation

    • html code

      Add "modify function" code in stuList.html

      //Modify data function
                  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 => {
                              //Assign the queried data to tableData
                              this.tableData = resp.data.list;
                              //Set paging parameters
                              //Current page
                              this.pagination.currentPage = resp.data.pageNum;
                              //Total number
                              this.pagination.total = resp.data.total;
                          })
                      //Close the edit window
                      this.dialogTableVisible4edit = false;
                  }
      
      
    • java code

      • 1. Add "modification function" - updatestau in StudentServlet.java
          /*
              Modify data function
           */
          private void updateStu(HttpServletRequest req, HttpServletResponse resp) {
              //Get request parameters
              Map<String, String[]> map = req.getParameterMap();
              String currentPage = req.getParameter("currentPage");
              String pageSize = req.getParameter("pageSize");
      
              //Encapsulating Student objects
              Student stu = new Student();
      
              //Registration date converter method
              dateConvert();
      
              try {
                  BeanUtils.populate(stu,map);
              } catch (Exception e) {
                  e.printStackTrace();
              }
      
              //Call the modification method of the business layer
              service.updateStu(stu);
      
              //Redirect to paging query function
              try {
                  resp.sendRedirect(req.getContextPath() + "/studentServlet?method=selectByPage&currentPage=" + currentPage + "&pageSize=" + pageSize);
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      
      
      • 2. Add "modification function" - updatestau in StudentService.java
      /*
              Modify data method
           */
          public abstract void updateStu(Student stu);
      
      
      • 3. "Modification function" - updatestau is added in StudentServiceImpl.java
      	/*
      	*1,Direct copy will report an error
      	*2,This line of code needs to be added to the "doGet" method
      	*3,Add the judgment of "updatestau" method name	
          */
      	else if(method.equals("updateStu")) {
                  //Add data function
                  updateStu(req,resp);
           }	
      ==================================================================================
      
      /*
              Modify data method
           */
          @Override
          public void updateStu(Student stu) {
              InputStream is = null;
              SqlSession sqlSession = null;
              try{
                  //1. Load the core configuration file
                  is = Resources.getResourceAsStream("MyBatisConfig.xml");
                  //2. Get SqlSession factory object
                  SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
                  //3. Obtain the SqlSession object through the SqlSession factory object
                  sqlSession = sqlSessionFactory.openSession(true);
                  //4. Get the StudentMapper interface implementation class object
                  StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
                  //5. Call the implementation class object modification method
                  mapper.updateStu(stu);
              } catch (Exception e) {
                  e.printStackTrace();
              } finally {
                  //6. Release resources
                  if(sqlSession != null) {
                      sqlSession.close();
                  }
                  if(is != null) {
                      try {
                          is.close();
                      } catch (IOException e) {
                          e.printStackTrace();
                      }
                  }
              }
          }
      
      
      • 4. "Modification function" - updatestau is added in StudentMapper.java
      /*
              Modify data method
           */
          @Update("UPDATE student SET number=#{number},name=#{name},birthday=#{birthday},address=#{address} WHERE number=#{number}")
          public abstract void updateStu(Student stu);
      
      

2.6 implementation of deletion function

  • code implementation

    • html code

      Add "delete function" code in stuList.html

      //Delete data function
                  deleteStu(row) {
                      if(confirm("Are you sure you want to delete" + row.number + "data?")) {
                          let param = "method=deleteStu&number=" + row.number +
                              "&currentPage=" + this.pagination.currentPage + "&pageSize=" + this.pagination.pageSize;
                          axios.post("studentServlet",param)
                              .then(resp => {
                                  //Assign the queried data to tableData
                                  this.tableData = resp.data.list;
                                  //Set paging parameters
                                  //Current page
                                  this.pagination.currentPage = resp.data.pageNum;
                                  //Total number
                                  this.pagination.total = resp.data.total;
                              })
                      }
                  }
      
      
    • java code

      • 1. Add "delete function" in StudentServlet.java-
      	/*
      	*1,Direct copy will report an error
      	*2,This line of code needs to be added to the "doGet" method
      	*3,Add the judgment of "deleteStu" method name	
          */
      	else if(method.equals("deleteStu")) {
                  //Add data function
                  deleteStu(req,resp);
           }	
      ==================================================================================
      
      
      /*
              Delete data function
           */
          private void deleteStu(HttpServletRequest req, HttpServletResponse resp) {
              //Get request parameters
              String number = req.getParameter("number");
              String currentPage = req.getParameter("currentPage");
              String pageSize = req.getParameter("pageSize");
      
              //Call the deletion method of the business layer
              service.deleteStu(number);
      
              //Redirect to paging query function
              try {
                  resp.sendRedirect(req.getContextPath() + "/studentServlet?method=selectByPage&currentPage=" + currentPage + "&pageSize=" + pageSize);
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      
      
      • 2. Add "delete function" in StudentService.java-
          /*
              Delete data method
           */
          public abstract void deleteStu(String number);
      
      
      • 3. Add "delete function" in StudentServiceImpl.java-
      /*
              Delete data method
           */
          @Override
          public void deleteStu(String number) {
              InputStream is = null;
              SqlSession sqlSession = null;
              try{
                  //1. Load the core configuration file
                  is = Resources.getResourceAsStream("MyBatisConfig.xml");
                  //2. Get SqlSession factory object
                  SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
                  //3. Obtain the SqlSession object through the SqlSession factory object
                  sqlSession = sqlSessionFactory.openSession(true);
                  //4. Get the StudentMapper interface implementation class object
                  StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
                  //5. Call the implementation class object deletion method
                  mapper.deleteStu(number);
              } catch (Exception e) {
                  e.printStackTrace();
              } finally {
                  //6. Release resources
                  if(sqlSession != null) {
                      sqlSession.close();
                  }
                  if(is != null) {
                      try {
                          is.close();
                      } catch (IOException e) {
                          e.printStackTrace();
                      }
                  }
              }
          }
      
      • 4. Add "delete function" in StudentMapper.java-
          /*
              Delete data method
           */
          @Delete("DELETE FROM student WHERE number=#{number}")
          public abstract void deleteStu(String number);
      

Posted by DJH on Wed, 01 Dec 2021 19:51:28 -0800