Vue and Element use

Getting started with Vue

3.0   2.0 Differences between
1.Smaller core library 


MVVM MVC The difference between the two
MVVM Connect the front-end model

Bubbling event
HTML There is the concept of parent-child elements in

meaning

Is a lightweight framework, more simple.

Differences between JQuery and VUE

Jquery He operates data with the need to operate dom

Vue It is mainly oriented to data operation and does not need to dom Operate
  • v-html (operation ordinary text)

    • Function: analyze the label and store the variable content in the text of the label
    • {{}: bind variables directly and display the data directly at the symbol out =
  • v-bind (attribute value of operation tag) [attr, prop, setAttribute]

format

Guide package required

Define template

  1. Create Vue object to specify the scope of Vue
  2. The el attribute specifies the element object that needs to be bound
  3. Write corresponding data
  4. Write corresponding methods

Note: since Vue does not need to operate on the label, use {Name}} to automatically replace the data value saved in data

 let vm = new Vue({
        el:"#div ", / / get scope   
        data:{  	 //Define data
            msg:"Zhang San",
        },
        methods: {
     		//No, you can't write. You can use this to manipulate the data in this scope
 		}
    });
<body>
    <!-- view -->
    <div id="div">  
        {{msg}}   //Similar to html text, you can operate on the text of the tag. Why does the msg value of the data attribute in Vue automatically display what value
    </div>
</body>

Vue method is a simplified method

 The first way
methods:{
            study: function(){
                alert(this.name + "Is" + this.classRoom + "study hard!");
            }
}
Practical simplification
methods:{
            study(){
                alert(this.name + "Is" + this.classRoom + "study hard!");
            }
        }

instructions

attribute effect
v-html If you set the label body with a label, you will assign {} to the label body with an effective value
v-bind Bind attribute values for tags
v-if Set whether the label appears. If it does not appear, no label will be generated
v-else-if Set whether the label appears. If it does not appear, no label will be generated
v-else Set whether the label appears. If it does not appear, no label will be generated
v-show Set whether the label is hidden (the label will be generated)
v-for Traverse the data and generate labels
v-on Bind events for tags
v-model Two way binding data value, cannot be used with v-bind:value at the same time

v-html

Function: assign a value to the content of the label. If the content contains a label, the corresponding label effect will be displayed

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Quick start upgrade</title>
    <script src="../../../vue.js"></script>
</head>
<body>
    <!-- view -->
    <div id="div">
        <div v-html="sign"></div>   -- Add child labels to the label body
        <div >full name:{{name}}</div>
        <div>Class:{{classRoom}}</div>
        <button onclick="hi()">say hello</button>   -- Use later v-on For binding events, use native js Bind in the same way
        <button onclick="update()">Modify class</button>
    </div>
</body>

<script>
    // script
    let vm = new Vue({
        el:"#div",
        data:{
            sign:"<a href='www.baidu.com'>use Baidu Search</a>",
            name:"Zhang San",
            classRoom:"Dark horse programmer"
        },
        methods:{
            study(){
                alert(this.name + "Is" + this.classRoom + "study hard!");   //This represents this Vue object
            }
        }
    });

    //Define greeting method
    function hi(){
        vm.study();
    }

    //Define and modify class
    function update(){
        vm.classRoom = "Intelligence Podcast";
    }
</script>
</html>

v-bind

Function: adding attribute values to a tag can be written in a simplified way, which can be assigned directly or by using the data of data

<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Binding properties</title>
 6   <style>
        .my{
            border: 1px solid red;   //Class style
        }
    </style>
</head>
<body>
    <div id="div">
         <a v-bind:href="www.baidu.com">use Baidu Search</a>
        <a v-bind:href="url">use Baidu Search</a>
        <br>
        <a :href="url">use Baidu Search</a>    -- Most of the simplified writing methods use this kind of writing method
        <br>
        <div :class="cls">I am div</div>   --  add to class Property to append a class style to it
    </div>
</body>
<script src="js/vue.js"></script>
<script>
    new Vue({
        el:"#div",
        data:{
            url:"https://www.baidu.com",
            cls:"my"
        }
    });
</script>
</html>

v-if/else/else-if/show

V-IF / else / else if function: judge the condition. If it is true, a label will be generated.

show function: judge it. If it is true, change the display to display, otherwise it will not be displayed

  • difference

    if it is determined as false, no label will be generated

show whether it is true or false, a label will be generated, but whether it will be displayed

<div id="d">
    <div v-if="login">center</div>   //True tags are generated; false tags are not generated
    <div v-else-if="!login" :class="cls">  
        <div>zhuce</div>
        <div>denglu</div>
    </div>
</div>
<script>
   let v = new Vue({
        el:"#d",
        data:{
            login:true
        }
    });
</script>

v-for

Function: it can generate data circularly. Each data generated is an element

   You can traverse the array or{}Object.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>List rendering</title>
    <script src="../../../vue.js"></script>

</head>
<body>
    <div id="div">
        <ul>
            <li v-for="name in names">
                {{name}}
            </li>
            <li v-for="value in student">    //  student is the key in data, and value is each value traversed
                {{value}}
            </li>
        </ul>
    </div>
</body>
<script src="js/vue.js"></script>
<script>
    new Vue({
        el:"#div",
        data:{
            names:["Zhang San","Li Si","Wang Wu"],
            student:{
                name:"Zhang San",
                age:23
            }
        }
    });
</script>
</html>

v-on

Function: bind events for a tag

Abbreviations:

@ event name = "method name () / method name"

<!DOCTYPE html>
<html lang="en" xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Event binding</title>
</head>
<body>
    <div id="div">
        <div>{{name}}</div>
        <button v-on:click="change()">change div Content of</button>
        <button v-on:dblclick="change()">change div Content of</button>

        <button @click="change()">change div Content of</button>
    </div>
</body>
<script src="js/vue.js"></script>
<script>
    new Vue({
        el:"#div",
        data:{
            name:"Dark horse programmer"
        },
        methods:{
            change(){
                this.name = "Intelligence Podcast"
            }
        }
    });
</script>
</html>

v-model

Function: bidirectional assignment. Whenever the value of one end is modified, the other end will be modified automatically.

: model = "" simplified writing bidirectional binding ""

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Form binding</title>
</head>
<body>
    <div id="div">
        <form autocomplete="off">
            full name:<input type="text" name="username" v-model="username">  //When the page is refreshed in the form item, Zhang San will appear
            																Once modified, the data The data was also modified
            <br>
            Age:<input type="number" name="age" v-model="age">
        </form>
    </div>
</body>
<script src="js/vue.js"></script>
<script>
    new Vue({
        el:"#div",
        data:{
            username:"Zhang San",
            age:23
        }
    });
</script>
</html>

Getting started with element UI

Element official website: https://element.eleme.cn/#/zh-CN

Element UI usage

The core use of element is

Guide Package

  1. Import the core CSS file into index css
  2. First import the JS file vue js
  3. Import your own js
  4. Find the appropriate label on the official website and copy and paste it

be careful:

Element UI is dependent on Vue. All element tags must be defined in Vue containers, such as div

For the code found on the official website, the tag part can be dragged out directly, while the data in the script tag only needs to be dragged into the part of return {}. Pay attention to whether it is necessary

Pay attention to the layout when using the container tag

 **use header perhaps footer It is arranged vertically, otherwise it is arranged horizontally**

 **use aside The label is laid out on the side**

When using the main tag, the layout is in the main area

Case:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Student list</title>
    //Here are three core files to import
    <link rel="stylesheet" href="element-ui/lib/theme-chalk/index.css">
    <script src="js/vue.js"></script>  
    <script src="element-ui/lib/index.js"></script>
    
    <style>
      .el-header{
        background-color: #545c64;
      }
      .header-img{
        width: 100px;
        margin-top: 20px;
      }
    </style>
</head>
<body>
  <div id="div">
    <el-container>
      <!-- head -->
      <el-header class="el-header">
        <el-container>
          <div>
            <el-image src="img/export.png" class="header-img"></el-image>
          </div>
          <el-menu
            :default-active="activeIndex2"
            mode="horizontal"
            @select="handleSelect"
            background-color="#545c64"
            text-color="white"
            active-text-color="#ffd04b"
            style="margin-left: auto;">
            <el-menu-item index="1">Processing center</el-menu-item>
            <el-submenu index="2">
              <template slot="title">My workbench</template>
              <el-menu-item index="2-1">Option 1</el-menu-item>
              <el-menu-item index="2-2">Option 2</el-menu-item>
              <el-menu-item index="2-3">Option 3</el-menu-item>
            </el-submenu>
            <el-menu-item index="3"><a href="Student list.html" target="_self">home page</a></el-menu-item>
          </el-menu>
        </el-container>
      </el-header>

      <!-- Sidebar area -->
      <el-container style="height: 580px; border: 1px solid #eee">
        <el-aside width="200px" style="background-color: rgb(238, 241, 246)">
          <el-menu :default-openeds="['1']">
            <el-submenu index="1">
              <template slot="title"><i class="el-icon-menu"></i>School Work Department</template>
              <el-menu-item-group>
                <el-menu-item index="1-1"><i class="el-icon-help"></i>Student management in school</el-menu-item>
                <el-menu-item index="1-2"><i class="el-icon-help"></i>Student upgrade/Repeat a grade</el-menu-item>
                <el-menu-item index="1-3"><i class="el-icon-help"></i>Student employment</el-menu-item>
              </el-menu-item-group>
            </el-submenu>
            <el-submenu index="2">
              <template slot="title"><i class="el-icon-menu"></i>Consulting Department</template>
              <el-menu-item-group>
                <el-menu-item index="2-1"><i class="el-icon-help"></i>Intentional student management</el-menu-item>
                <el-menu-item index="2-2"><i class="el-icon-help"></i>Management of unregistered students</el-menu-item>
                <el-menu-item index="2-3"><i class="el-icon-help"></i>Registered student management</el-menu-item>
              </el-menu-item-group>
            </el-submenu>
            <el-submenu index="3">
              <template slot="title"><i class="el-icon-menu"></i>Teaching and Research Department</template>
              <el-menu-item-group>
                <el-menu-item index="3-1"><i class="el-icon-help"></i>Existing course management</el-menu-item>
                <el-menu-item index="3-2"><i class="el-icon-help"></i>Developing course management</el-menu-item>
                <el-menu-item index="3-3"><i class="el-icon-help"></i>New technology curriculum management</el-menu-item>
              </el-menu-item-group>
            </el-submenu>
          </el-menu>
        </el-aside>
        
        <!-- Main area -->
        <el-container>
          <el-main>
            <b style="color: red;font-size: 20px;">Student list</b>
            <div style="float:right">
              <el-button type="primary">Add student</el-button>
            </div>
            <el-table :data="tableData">
              <el-table-column prop="date" label="date" width="140">
              </el-table-column>
              <el-table-column prop="name" label="full name" width="120">
              </el-table-column>
              <el-table-column prop="address" label="address">
              </el-table-column>
              <el-table-column
                label="operation"
                width="180">
                <el-button type="warning">edit</el-button> 	//Added button style        
                <el-button type="danger">delete</el-button>     //Added button style        
              </el-table-column>
            </el-table>
          </el-main>
        </el-container>
      </el-container>
    </el-container>
  </div>
</body>
<script>
    new Vue({
        el:"#div",
        data:{
          tableData:[
            {
              date:"2088-08-08",
              name:"Zhang San",
              address:"Changping District, Beijing"
            },{
              date:"2088-08-08",
              name:"Li Si",
              address:"Changping District, Beijing"
            },{
              date:"2088-08-08",
              name:"Wang Wu",
              address:"Changping District, Beijing"
            },
          ]
        }
    });
</script>
</html>

Vue advanced part

Custom components

In the element UI, all tags are automatically labeled

Custom label format

Vue.component(Component name, {
	props:Properties of components,
	data: Data function of component,
	template: Label template resolved by component 
						}) 
<!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:["name","style"],
        // Data function
        data: function(){
            return{
                msg:"My button"
            }
        },
        //Parsing label templates
        template:"<div>
        <button style='color:red'>{{msg}}</button>  //The msg here is already specified when encoding
        <button >{{props.name}}</button>   //The name here is entered by the user
   				 </div>"
    });

    new Vue({
        el:"#div"
    });
   
</script>
</html>

Note: the definition format should also be written in the Vue container.

Only one can be defined in the template, so it should be installed with div. The elements defined in props can be used in the template.

Lifecycle method (hook function)

Is an independent function that exists outside the methods {} method. There are four others, namely beforeCreated and so on.

The mounted function can be used as a global refresh function.

  1. Created (vue real column is created, and the page has not been loaded or parsed)
  2. mounted (the function at this time is to complete the template parsing)
  3. updated
  4. destroyed

Asynchronous requests from Vue

Asynchronous requests using Vue need to import the axios package

Note: the only method for asynchronous request here is get There are two kinds of post.

There are only two callback functions, success response and failure response then() .catch()

resp in the callback function needs to be data is the object of the callback function.

This in asynchrony represents the current Vue object. You can use this to find all properties, such as variable names in data and method names in methods.

When using events, you can pass props Row means to send all data of this line together.

  updateStu() {
      			//Define parameters
                let param = "method=updateStu&number=" + this.editFormData.number + "&name=" + this.editFormData.name +"&birthday=" + this.editFormData.birthday + "&address=" + this.editFormData.address;
    			  //Start asynchronous request
                axios.post("studentServlet",param)	  //Use post. Because it is in the request body, it is written separately.
   			    axios.get("studentServlet?"+param)	  //Use the get method, because it is in the address bar, so? Heel parameter
                    .then(resp => {
                        if(resp.data == true) {
                            this.selectByPage()   //Re query the page after receiving
                        }
                    })
                //Close the edit window 
                this.dialogTableVisible4edit = false;   //Display page
            }

Use of iframe

Function: it can embed other pages in the current page

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>hello world</h1>
<iframe src="login.html" frameborder="false" style="top:80px;left: 120px; width: 100%;height:500px"></iframe>
</body>
</html>

Asynchronous request case

Anterior segment

The paging plug-in is used in this case.

When using events, you can pass props Row means to send all data of this line together. The details are as follows

be careful:

When clicking the edit box, if the undefined attribute value cannot be directly assigned in the showEditStu method, the data can be echoed, but the page will get stuck. Because all the data in editFormData {} has not been defined until the moment of opening. Therefore, if you want to assign values, you can only assign values to editFormData as a whole, or use this$ Set (this.editFormData, "built-in attribute name", "attribute value") to assign values one by one.

When debugging in the front-end web page, you can use ctrl+shift+C to click the corresponding element to directly jump to the corresponding front-end code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Student management system</title>
    <link rel="stylesheet" href="element-ui/lib/theme-chalk/index.css">
    <script src="js/vue.js"></script>
    <script src="element-ui/lib/index.js"></script>
    <script src="js/axios-0.18.0.js"></script>
    </head>
    <body>
    <div id="div">
    <b style="color: red; font-size: 20px;">Student list</b>
    <div style="float: right;">
        <el-button type="primary" @click="showAddStu">Add student</el-button>
    </div>
    <el-table :data="tableData">
        <el-table-column prop="number" label="Student number" width="120">
        </el-table-column>
        <el-table-column prop="name" label="full name" width="120">
        </el-table-column>
        <el-table-column prop="birthday" label="birthday" width="140">
        </el-table-column>
        <el-table-column prop="address" label="address">
        </el-table-column>
        <el-table-column label="operation" width="180">
          <template slot-scope="props">
		<el-button type="warning" @click="showEditStu(props.row)">edit</el-button>    //Note here props Use of row
              <el-button type="danger" @click="deleteStu(props.row)">delete</el-button>
          </template>
        </el-table-column>
    </el-table>

    <!--
        Paging component
          @size-change:  Function triggered when changing the number of entries per page
          @current-change: Function triggered when page number is changed
          current-page : Default page number
          :page-sizes: The value displayed in the number of entries per page selection box
          :page-size : Default number of entries per page
          layout:  Layout of paging components
              total(Total number), sizes(Number of entries per page), prev((previous page), pager(All page numbers), next(next page), jumper(Jump page)
          :total: Total number
    -->
    <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pagination.currentPage"
            :page-sizes="[3,5,8]"
            :page-size="pagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total">
    </el-pagination>

    <el-dialog title="Add student information" :visible.sync="dialogTableVisible4add" @close="resetForm('addForm')">
        <!--
            :model="formData": Associated data
            :rules: Association verification rules
            ref:  Used when getting form objects
        -->
        <el-form :model="formData" :rules="rules" ref="addForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="Student number" prop="number">
                <el-input v-model="formData.number"></el-input>
            </el-form-item>
            <el-form-item label="Student name" prop="name">
                <el-input v-model="formData.name"></el-input>
            </el-form-item>
            <el-form-item label="Student birthday" prop="birthday">
                <!--v-model : Bidirectional binding -->
                <el-input v-model="formData.birthday" type="date"></el-input>
            </el-form-item>
            <el-form-item label="Student address" prop="address">
                <el-input v-model="formData.address"></el-input>
            </el-form-item>
            <el-form-item align="right">
                <el-button type="primary" @click="addStu()">add to</el-button>
                <el-button @click="resetForm('addForm')">Reset</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>

    <el-dialog title="Edit student information" :visible.sync="dialogTableVisible4edit" @close="resetForm('editForm')" >
        <!--
            :model="formData": Associated data
            :rules: Association verification rules
            ref:  Used when getting form objects
        -->
        <el-form :model="editFormData" :rules="rules" ref="editForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="Student number" prop="number">
                <el-input v-model="editFormData.number"></el-input>
            </el-form-item>
            <el-form-item label="Student name" prop="name">
                <el-input v-model="editFormData.name"></el-input>
            </el-form-item>
            <el-form-item label="Student birthday" prop="birthday">
                <!--v-model : Bidirectional binding -->
                <el-input v-model="editFormData.birthday" type="date"></el-input>
            </el-form-item>
            <el-form-item label="Student address" prop="address">
                <el-input v-model="editFormData.address"></el-input>
            </el-form-item>

            <el-form-item align="right">
                <el-button type="warning" @click="updateStu()">modify</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</div>
</body>
<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 items displayed 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:{
            //
            showEditStu(row){
                this.dialogTableVisible4edit=true;
                // Display all the displayed data here;
                this.editFormData.number=row.number;
                this.editFormData.name=row.name;
                this.editFormData.birthday=row.birthday;    //This method cannot be used here, which will cause the page to jam and cannot be input
                this.editFormData.address=row.address;		//Reason: when editFormData is assigned, it has not been created.
                //
                // this.editFormData = {
                //     number:row.number,
                //     name:row.name,
                //     birthday:row.birthday,
                //     address:row.address,
                // }
            },
            //to update
            updateStu(){
                //Because the two-way binding is too, it will be updated automatically
                let parm="method=updateStu&number="+this.editFormData.number+"&name=" + this.editFormData.name +
                    "&birthday=" + this.editFormData.birthday + "&address=" + this.editFormData.address;
                //Asynchronous request
                axios.post("/studentServlet",parm)
                    .then(resp =>{
                        //Judge whether the update is successful
                        if(resp.data==true){
                        //If successful, query again
                            this.selectByPage();
                        }
                    });
                //Hide update window
                this.dialogTableVisible4edit=false;
            },
            deleteStu(props){
               if (confirm("Are you sure you want to delete it"+props.number+"This record")){
                axios.post("/studentServlet","method=deleteStu&id="+props.number)
                    .then(resp => {
                        //Judge true and false
                        if(resp.data == true){
                            //Re query for true
                            this.selectByPage();
                        }else {
                            alert("Something's wrong. Please try again later");
                        }
                    })}
            },
            //Paging query function
            selectByPage(){
                axios.post("/studentServlet","method=selectByPage&currentPage="+this.pagination.currentPage
                    +"&pageSize="+this.pagination.pageSize)
                    .then(resp =>{
                         this.tableData= resp.data.list;
                         this.pagination.currentPage=resp.data.pageNum;
                         this.pagination.total=resp.data.total;
                    })
            },
            addStu(){
                    //Asynchronous request to add students
                let parm="method=addStu&number="+this.formData.number+"&name=" + this.formData.name +
                    "&birthday=" + this.formData.birthday + "&address=" + this.formData.address;

                axios.post("/studentServlet",parm)
                    .then(resp =>{
                       //Judge true and false
                        if(resp.data == true){
                        //Re query for true
                            this.selectByPage();
                        }else {
                            alert("Something's wrong. Please try again later");
                        }
                    });
                //Hide add box
                this.dialogTableVisible4add=false;
            },
            showAddStu(){
                //The add box is displayed
                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();
            },
            //Function executed when changing the number of entries per page
            handleSizeChange(pageSize) {
                //Modify the parameters of paging query
                this.pagination.pageSize = pageSize;
                //Re execute query
                this.selectByPage();
            },
            //Function executed when changing page number
            handleCurrentChange(pageNum) {
                //Modify the parameters of paging query
                this.pagination.currentPage = pageNum;
                //Re execute query
                this.selectByPage();
            },
        },
        mounted(){
            //Call paging query function
            this.selectByPage();
        }
    })
</script>
</html>

back-end

@WebServlet("/studentServlet")
public class StudentServlet extends HttpServlet {
    private  Service service = new Service();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Set request and response codes
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        //Get method
        String method = req.getParameter("method");
        //Determine the name and execute the corresponding method
        if("selectByPage".equals(method)){
            selectByPage(req, resp);
        }else if("addStu".equals(method)){
            addStu(req, resp);
        }else if("deleteStu".equals(method)){
            deleteStu(req, resp);
        }else if("updateStu".equals(method)){
            updateStu(req, resp);
        }

    }

    /*
        Delete data function
     */
    private void deleteStu(HttpServletRequest req, HttpServletResponse resp) {
        String id = req.getParameter("id");
//        int i = Integer.parseInt(id);
        Boolean aBoolean = service.deleteStu(id);
        if(aBoolean){
            try {
                resp.getWriter().write("true");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            try {
                resp.getWriter().write("false");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /*
        Modify data function
     */
    private void updateStu(HttpServletRequest req, HttpServletResponse resp) {
        Map<String, String[]> parameterMap = req.getParameterMap();
        Student student = new Student();
        try {
            BeanUtils.populate(student,parameterMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        int i = service.updateStu(student);
        if(i==1){
            try {
                resp.getWriter().write("true");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /*
        Add data function
     */
    private void addStu(HttpServletRequest req, HttpServletResponse resp) {
        //Get number
        String id = req.getParameter("number");
        //Get name
        String name = req.getParameter("name");
        //Get birthday
        String birthday = req.getParameter("birthday");
        //Get address
        String address = req.getParameter("address");

        //Call the business layer and instantiate the object to pass in
        Boolean aBoolean = service.addStu(new Student(id, name, java.sql.Date.valueOf(birthday), address));

        PrintWriter writer=null;;
        try {
             writer = resp.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //Judge whether it is added successfully
        if(aBoolean){
             //Return the corresponding result of the front end
            try {
                resp.getWriter().write("true");
            } catch (IOException e) {
                e.printStackTrace();
            }

        }else {
            //Return the corresponding result of the front end
            writer.write("false");
        }
    }

    /*
        Paging query function
     */
    private void selectByPage(HttpServletRequest req, HttpServletResponse resp) {
        //Get the current number of pages
        String currentPage = req.getParameter("currentPage");
        //Get page display size
        String pageSize = req.getParameter("pageSize");

        //Call the business layer method and pass in the parameters
        Page page = service.selectByPage(Integer.parseInt(currentPage), Integer.parseInt(pageSize));

        //Encapsulated as PageInfo
        PageInfo pageInfo = new PageInfo(page);

        try {
        //Convert the returned page object to json
        ObjectMapper objectMapper = new ObjectMapper();
            String s = objectMapper.writeValueAsString(pageInfo);
        //Return to front end
            resp.getWriter().write(s);
        } catch (Exception 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);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}

   //Encapsulated as PageInfo
    PageInfo pageInfo = new PageInfo(page);

    try {
    //Convert the returned page object to json
    ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(pageInfo);
    //Return to front end
        resp.getWriter().write(s);
    } catch (Exception 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);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    doGet(req,resp);
}

}

Posted by xeno on Thu, 12 May 2022 05:26:31 +0300