Database and SpringBoot foundation 02

Example 1: realize the function of registration and login

Home page:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>Project Homepage</h1>
<a href="/reg.html">register</a>
<a href="/login.html">Sign in</a>
</body>
</html>

Registration page:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>Registration page</h1>
<div>
  <input type="text" v-model="user.username" placeholder="enter one user name">
  <input type="text" v-model="user.password" placeholder="Please input a password">
  <input type="text" v-model="user.nick" placeholder="Please enter a nickname">
  <input type="button" value="register" @click="reg()">
</div>
<script src="js/vue.js"></script>
<script src="js/axios.min.js"></script>
<script>
    let v = new Vue({
        el:"div",
        data:{
            user:{
                username:"",
                password:"",
                nick:""
            }
        },
        methods:{
            reg(){
                //Send a post to submit the user object containing the user information
                axios.post("/reg",v.user).then(function (response){
                    //If the registration is successful, return to the home page
                    if(response.data==1){
                        alert("login was successful!")
                        //Let the browser display to the home page
                        location.href="/";
                    }else{
                        alert("User name already exists!");
                    }
                })
            }
        }
    })
</script>
</body>
</html>

Login page:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>Login page</h1>
<div>
  <input type="text" v-model="user.username" placeholder="user name">
  <input type="text" v-model="user.password" placeholder="password">
  <input type="button" value="Sign in" @click="login()">
</div>
<script src="js/vue.js"></script>
<script src="js/axios.min.js"></script>
<script>
  let v = new Vue({
    el:"div",
    data:{
      user:{
        username:"", password:""
      }
    },
      methods:{
        login(){
          //Issue asynchronous post request
            axios.post("/login",v.user).then(function (response){
                //If the login is successful, return to the home page
                if(response.data==1){
                    alert("Login successful!")
                    //Let the browser display to the home page
                    location.href="/";
                }else if(response.data==2){
                    alert("user name does not exist!");
                }else{
                    alert("Password error!")
                }
            })
        }
      }

  })
</script>
</body>
</html>

Function realization class;

@RestController
public class UserController {
    @Autowired
    UserMapper mapper;

    @RequestMapping("/reg")
    public int reg(@RequestBody User user){
        User u = mapper.selectByUsername(user.getUsername());
        if(u!=null){
            return 2;//"User name already exists!"
        }
        //Perform registration
        mapper.insert(user);
        return 1;//"Registration succeeded!"
    }

    @RequestMapping("/login")
    public int login(@RequestBody User user){
        //Take the user name entered by the user to query the user information in the database
        User u = mapper.selectByUsername(user.getUsername());
        if(u!=null){ //Represents that the user information is queried
            //Judge whether the password entered by the user is consistent with the queried password
            if(user.getPassword().equals(u.getPassword())){
                return 1;//Login succeeded!
            }
            return 3;//Wrong password!
        }
        return 2;//The representative user name does not exist
    }

}

mapper class:

@Mapper
public interface UserMapper {
    //If the return value is an object instead of a List collection, the query results must be 0 or 1
    //If there is more than one, an error will be reported
    @Select("select *from user where username=#{username}")
    User selectByUsername(String username);

    @Insert("insert into user values(null,#{username},#{password},#{nick})")
    void insert(User user);

}

User class:

 

Back end MVC design pattern

  • The code to realize a business is divided into three parts: page correlation (V), business logic correlation (C) and data correlation (M)
  • M:Model data model, the corresponding code is the Mapper part related to the database
  • 5: View view, corresponding to all page related contents
  • C: The Controller corresponds to the Controller related code
  • Order of realizing a business: V page related code - > C controller related code - > m database Mapper related code
  • When troubleshooting, you also find problems from these three parts of code
  • The back-end MVC involves V pages in the pattern, and the front-end engineer divides the page into three parts of MVC

Front and rear end separation

If the front and back ends are not separated, the back-end server needs two sets of code to deal with the mobile client and browser client, because the requirements of different clients are different, so the development efficiency of the back-end will be affected

Separation of front end and back end: it means that the relevant contents of the page are no longer processed in the Controller. The browser client needs to request the page first. After the page is loaded, it sends a request again from the page to obtain the data. After obtaining the data, it displays the data in the page. This process belongs to the local refresh of the page. The synchronous request can only refresh the page as a whole, but cannot refresh locally. Therefore, the synchronous request will not be used in the future, and all asynchronous requests will be used, Because the future work is basically the idea of separating the front and back

JSON

  • JSON is a lightweight data exchange format (data encapsulation format)
  • The client and server need to transfer data to each other. When complex data needs to be transferred, the data needs to be encapsulated according to a specific format. JSON is such a general format

Login successful

User name already exists

Password error

1

2

3

"id=1, title = mobile phone, price=1000, saleCount=500"

[{"id":1,"title": "ADI socks", "price":10.0,"saleCount":1000},{"id":3,"title": "pants", "price":50.0,"saleCount":400},{"id":4,"title": "socks", "price":5.0,"saleCount":100}]

How to transfer complex data between server and client

 

Steps for adding products in product management:

1. Create 3 checkmarks for the project and modify the application Properties configuration file, whether the project test is started successfully

2. Create index HTML home page and insert HTML page

3. In insert Add three text boxes and an add button to the HTML page to manage the page content through Vue. At this time, you need to copy the js folder in the previous project to the new project. When you click the Add button, send an asynchronous post request to the / insert address to submit the product information entered by the user

4. Create controller The productcontroller adds an insert method to handle / insert requests, creates a Product entity class, and declares in the insert method the parameter used to receive the passed parameter (this parameter needs to be modified with the @ RequestBody annotation)

5. Create ProductMapper, add Insert method in it, and modify it with @ Insert annotation

6. Assemble the ProductMapper in the Controller, and call the mapper's insert method in the insert method to pass the received Product object

Steps for managing product list:

1. In index Add a product list hyperlink to the HTML page. The request address is / list HTML page

2. Create list HTML page, add tables in the page and manage them through Vue. Issue asynchronous get requests in Vue's created method, give the requested data to an array variable, and then bind the contents of the table in the page with the data variables. When the array has values, the page will automatically display the data

3. Add a select method to the ProductController to process /select requests. In the method, call the select method of the mapper to directly return the List collection to the client

4. Implement the select method in mapper

To delete a product in product management:

1. Add the deleted hyperlink in the product list page, discard the jump function of the hyperlink, add a click event, call the del method, send an asynchronous get request to / delete in the method, and pass the id of the product

2. Add a delete method to the ProductController to process /delete requests. Call the deleteById method of the mapper in the method to pass in the received id

3. Implement the deleteById method in mapper

Steps for modifying commodities in commodity management:

1. Add and modify hyperlinks to the list page to / update The HTML page jumps and passes the past product id

2. Create update The HTML page gets the passed id in Vue's created method, then sends an asynchronous get request to / selectById, passes the id, receives the data returned by the service with a product object, and binds the page content with this object, so that the page with value can be displayed

3. Add a selectById method in ProductController to process /selectById requests, and call Mapper's selectById method in the method

4. Implement the selectById method in mapper

5. To update Click the Modify button in the HTML page to add a click event. When clicking, send an asynchronous post request to the / update address to submit the commodity information together

6. Add the update method in the ProductController to process the / update request, and use the mapper's update method in the method

7. Implement the update method in mapper

Example 2: commodity management example

Home page:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>Commodity Management Homepage</h1>
<a href="/insert.html">Add item</a>
<a href="/list.html">Product list</a>
</body>
</html>

Add product page:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>Add item</h1>
<div>
  <input type="text" v-model="p.title" placeholder="Product title">
  <input type="text" v-model="p.price" placeholder="commodity price">
  <input type="text" v-model="p.saleCount" placeholder="Commodity sales">
  <input type="button" value="add to" @click="insert()">
</div>
<script src="js/vue.js"></script>
<script src="js/axios.min.js"></script>
<script>
    let v = new Vue({
        el:"div",
        data:{
            p:{
                title:"",
                price:"",
                saleCount:""
            }
        },
        methods:{
            insert(){
                //Make asynchronous request
                axios.post("/insert",v.p).then(function (response){
                    alert("Add complete!")
                    location.href="/";
                })
            }
        }
    })
</script>
</body>
</html>

Product list page:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1> Product list</h1>
<table border="1">
  <tr>
    <th>commodity id</th>
    <th>Product title</th>
    <th>commodity price</th>
    <th>Commodity sales</th>
      <th>operation</th>
  </tr>
    <tr v-for="p in arr">
        <td>{{p.id}}</td>
        <td>{{p.title}}</td>
        <td>{{p.price}}</td>
        <td>{{p.saleCount}}</td>
        <!--javascript:void(0):Skip the function of super connection-->
        <td><a href="javascript:void(0)" @click="del(p.id)">delete</a>
            <!--Clicking modify needs to jump to the page, so the jump function cannot be abolished as deleting-->
            <!--If there are variables in the attributes of the element, attribute binding is required-->
            <a :href="'/update.html?id='+p.id">modify</a>
        </td>
    </tr>
</table>
<script src="js/vue.js"></script>
<script src="js/axios.min.js"></script>
<script>
    let v = new Vue({
        el:"table",
        data:{
            arr:[]
        },
        created:function (){//This method is executed when the Vue object is created
            //Generally, the code for loading the page request data will be written in this method
            //Issue asynchronous request to get data
            axios.get("/select").then(function (response){
                //The data returned by the server is directly sent to the arr array, because the page and array are bound
                //When the array value changes, the page will change automatically

                //The server passes binary data. The Axios framework will first convert the binary data back to a string in JSON format
                //After the string is converted, the string in JSON format will be converted into an array or object
                v.arr = response.data;
            })
        },
        methods:{
            del(id){
                //Asynchronous delete request
                axios.get("/delete?id="+id).then(function (response){
                    alert("Delete complete!");
                    location.reload();//Refresh page
                })
            }
        }
    })
</script>
</body>
</html>

Modify product page:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>Modify product page</h1>
<div>
  <input type="text" v-model="product.id" placeholder="id" readonly>
  <input type="text" v-model="product.title" placeholder="title">
  <input type="text" v-model="product.price" placeholder="Price">
  <input type="text" v-model="product.saleCount" placeholder="sales volume">
  <input type="button" value="modify" @click="update()">
</div>
<script src="js/vue.js"></script>
<script src="js/axios.min.js"></script>
<script>
  let v = new Vue({
    el:"div",
    data:{
        /*You can add attributes dynamically*/
        product:{}
    },
    created:function (){
        //After the page is loaded, get the id of the product, query the product information through the id and display it in the page
        //Get the id parameter from the address bar
      let id = location.search.split("=")[1];
        //Send an asynchronous request and query the corresponding product information through id
        axios.get("/selectById?id="+id).then(function (response){
            //Assign the product information queried by the server to the product variable in Vue
            //Bind the page to the product object. When the product gets the value, the page will be displayed
            v.product = response.data;
        })
    },
      methods:{
          update(){
              //Issue asynchronous post request
              axios.post("/update",v.product).then(function (response) {
                  alert("Modification completed!");
                  location.href="/list.html";
              })
          }
      }
  })
</script>
</body>
</html>

ProductController function implementation class:

import java.util.List;

@RestController
public class ProductController {
    @Autowired
    ProductMapper mapper;
    @RequestMapping("/insert")
    public void insert(@RequestBody Product product){
        System.out.println(product.toString());
        mapper.insert(product);
    }

    @RequestMapping("/select")
    public List<Product> select(){
        // When the spring MVC framework finds that the return value type is a collection or a custom object type,
        //The collection or object will be converted into JSON format string, and then the JSON format string will be converted into binary data for network transmission
        //[{"id":1,"title": "ADI socks", "price":10.0,"saleCount":1000},{"id":3,"title": "pants", "price":50.0,"saleCount":400},{"id":4,"title": "socks", "price":5.0,"saleCount":100}]
        List<Product> list = mapper.select();

        return list;
    }

    @RequestMapping("/delete")
    public void delete(int id){
        System.out.println("id = "+id);
        mapper.deleteById(id);
    }

    @RequestMapping("/selectById")
    public Product selectById(int id){
        System.out.println("id = "+id);
        //When the spring MVC framework finds that a custom object is returned, it will automatically convert it into a string in JSDN format
        return mapper.selectById(id);
    }

    @RequestMapping("/update")
    public void update(@RequestBody Product product){
        mapper.update(product);
    }

}

Product class:

mapper class:

import java.util.List;

@Mapper
public interface ProductMapper {
    @Insert("insert into product values(null,#{title},#{price},#{saleCount})")
    void insert(Product product);

    @Select("select *from product")
    @Result(property = "saleCount",column = "sale_count")
    List<Product> select();

    @Delete("delete from product where id=#{id}")
    void deleteById(int id);

    @Select("select *from product where id=#{id}")
    @Result(property = "saleCount",column = "sale_count")
    Product selectById(int id);

    @Update("update product set title=#{title},price=#{price},sale_count=#{saleCount} where id=#{id}")
    void update(Product product);
}

 

Example 3: realize file upload function

Home page:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <!-- import CSS -->
  <link rel="stylesheet" href="css/eui.css">
</head>
<body>
<div id="app">
  <!--name Represents the parameter name of the file when uploading the file-->
  <el-upload
          action="/upload"
          name="picFile"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove">
    <i class="el-icon-plus"></i>
  </el-upload>
  <el-dialog :visible.sync="dialogVisible">
    <img width="100%" :src="dialogImageUrl" alt="">
  </el-dialog>
</div>
</body>
<!-- import Vue before Element -->
<script src="js/vue.js"></script>
<!-- import JavaScript -->
<script src="js/eui.js"></script>
<script src="js/axios.min.js"></script>
<script>
  let v = new Vue({
    el: '#app',
    data: function() {
      return {
        dialogImageUrl: '',
        dialogVisible: false
      }
    },
    methods: {
      handleRemove(file, fileList) {
        console.log(file, fileList);
        //When you click Delete picture, the method will execute
        //File represents the file to be deleted
        //file.response represents the data (file name) that the server responds to when the file is uploaded successfully
        console.log("file name="+file.response);
        axios.get("/remove?name="+file.response).then(function (response) {
          console.log("The server image has been deleted")
        })
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      }
    }
  })
</script>
</html>
@RestController
public class UploadController {
    @RequestMapping("/upload")
    public String upload(MultipartFile picFile) throws IOException {
        System.out.println("picFile = " + picFile);
        //Get the original file name a.jpg
        String fileName = picFile.getOriginalFilename();
        //Get the last suffix The location of the occurrence is intercepted to the last
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //Get the unique file name UUID Randomuuid() gets a unique identifier
        fileName = UUID.randomUUID()+suffix;
        System.out.println("file name:"+fileName);
        //The path to the folder where the pictures are to be saved
        String dirPath = "F:/files";
        File dirFile = new File(dirPath);
        //If the folder does not exist, create it
        if (!dirFile.exists()){
            dirFile.mkdirs();//create folder
        }
        //Get the full path of the file
        String filePath = dirPath+"/"+fileName;
        //An exception is thrown when saving the file to this path
        picFile.transferTo(new File(filePath));
        System.out.println("File save complete! Please go to this path to check whether the file exists "+filePath);

        return fileName;
    }

    @RequestMapping("/remove")
    public void remove(String name){
        String dirPath = "F:/files";
        String filePath = dirPath+"/"+name;
        new File(filePath).delete();//Delete file
    }

}

 

Tags: Vue.js eureka elementUI

Posted by rsasalm on Fri, 13 May 2022 22:48:22 +0300