Add, delete, modify and query the mysql database through HTML web pages (CRUD instance)

First of all, we have to understand the general structure, as follows:

We develop from the bottom up,

First, write the mysql database first

Second, write the java backend (Spring MVC architecture) (it doesn’t matter if you don’t understand what this is, just follow the steps)

3. Finally, write the front-end page (HTML)

1. Mysql database part

We want to develop the database through the web page, then we need to prepare the database first.

In order to facilitate development, directly use navicat to create a database, the name is crud, and the character set is utf8

Then create a data table in the database. Let's take student information as an example and create a data table named student 

The list of fields is as follows:

 By the way, add some data to the database

In this way, we have finished the first part, light a cigarette and reward yourself~~

2. Write java backend code

1. Open IDEA and create a new spring project

 Check the web dependency, just check this

 After clicking Finish, open this link if an error is reported:

When IDEA creates a springboot project, it prompts that https://start.spring.io initialization failed - Programmer Sought

 2. Write the pom.xml file

Let's first find this "dependencies" tag

 Add dependent coordinates inside this tag.

This file is the external dependency used by the project. Let's analyze it:

To connect to the mysql database we need to add the driver:

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

In order to simplify the interaction, we also need to add the dependent coordinates of mybatis

        <dependency>
            <!--Springboot和MyBatis整合得ar包坐标-->
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>

There are also thymeleaf dependent coordinates for interacting with the front end

        <dependency>
            <!--和前端交互用的-->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

There are also some miscellaneous and useful dependencies

        <dependency>
            <!--德鲁伊数据源坐标-->
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.8</version>
        </dependency>

        <dependency>
            <!--注解开发自动导入的依赖   @Data那种 -->
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

final result: 

 

Then refresh the maven pom file and write it 

3. Build packages (3+1=4 packages)

MVC architecture: controller, service, mapper

Package for storing entity classes: pojo

 4. Create an entity class under pojo, and the attributes of the class should correspond to the fields of the data table

Create a Student class under pojo, and add three annotations to the class. The functions of these three annotations are

Add: get set method, construction method with parameters, construction method without parameters

 5. Configure the database connection information, through the yml file (pay special attention to the indentation inside, the indentation must be the same as what I wrote)

#数据库连接信息
spring:
  datasource:
    username: root
    password: 2633
    url: jdbc:mysql://localhost:3306/crud?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource

 result:

 5. Write mapper layer

(1) Create an interface named StudetMapper in mapper

(2) Add annotation @Mapper to the interface

 (3) Write the method of adding, deleting, modifying and checking in the interface

 6. Write SQL

(1) Install a mybatis plugin first

 

(2) First create a mapper directory in the following path, and then create a StudentMapper.xml file 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.example.crud.mapper.StudentMapper">



</mapper>

 After that, there will be a bird with a blue headband on the screen

 Click on the bird, it will jump to the StudentMapper interface, then we can see that the interface method reported an error

 (3) Write the sql statement in the mapper tag

Put the mouse cursor on the red place, press the shortcut key alt + enter to create a place to write sql, and then write sql in the label

(4) Connect to the database

 Then there will be no error.

Continue to write the SQL language, repeatedly return to the interface and press ALT+Enter+Enter to write all the SQL

 There is no error reported until here, and there is a bird with a red headband

 7. Add mybatis information to the application.yml file

#配置Mybatis映射路径
mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.example.StudentDemo.pojo

 Configure the port to be 80

#配置端口
server:
  port: 80

result

 

 8. Write the service layer

(1) Add the @Service annotation outside the class

(2) Add in the class

    @Autowired
    StudentMapper studentMapper;

(3) Call the interface method of studentMapper

Screenshot of the result: 

9. Write the controller layer and front-end page

Note: This is the hardest part in my opinion. If there is no unit test before, there may be an error, so unit test is very important

(1) Create a StudentController class in the controller and annotate it as @Controller outside the class

(2) Add the annotation @Autowired to the class to call StudentService

 StudentController code

package com.example.crud.controller;

import com.example.crud.pojo.Student;
import com.example.crud.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.List;

@Controller
public class StudentController {
    @Autowired
    StudentService studentService;

    @GetMapping("/toindex")
    public String toindex(){
        return "index";
    }

    //查询所有页面
    @GetMapping("/findStudentList")
    public String findStudentList(Model model){
        List<Student> studentList=studentService.findAllStudent();
        //传进去的是一个键值对
        model.addAttribute("studentList",studentList);//传进前端的东西
        //返回值==html文件名
        return "findStudentList";
    }

    //跳转到添加页面
    @GetMapping("/toaddStudent")
    public String toaddStudent(){
        //返回值为文件名
        return "addStudent";
    }

    //真正执行添加
    @PostMapping("/addStudent")
    public String addStudent(Student student)
    {
        studentService.addStudent(student);
        //跳转到哪里(文件名)
        return "redirect:/findStudentList";
    }

    @GetMapping("/toupdateStudent/{id}")
    public String toupdateStudent(@PathVariable("id")String id, Model model){
        //先找到被修改的对象
        Student student=studentService.findStudentById(id);
        //将对象保存到model中
        model.addAttribute("student",student);
        //html文件名
        return "updateStudent";
    }

    @PostMapping("/updateStudent")
    public String updateStudent(Student student){
        //获取当前页面学生信息,传入按照id修改学生信息的Service,进行信息修改
        studentService.updateStudent(student);
        return "redirect:/findStudentList";
    }

    @GetMapping("/deleteStudent/{id}")
    public String deleteStudent(@PathVariable("id")String id){
        studentService.deleteStudent(id);
        return "redirect:/findStudentList";
    }
}

 Results screenshot

(3) Write home page index.html

<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<a th:href="@{/findStudentList}">查询信息</a>
</body>
</html>

 (4) Write a query for all pages findStudentList.html

<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<!--/*@thymesVar id="student" type="com.example.crud.pojo.Student"*/-->
<!--/*@thymesVar id="studentList" type="com.example.crud.controller"*/-->
<head>
    <meta charset="UTF-8">
    <title>查询所有</title>
</head>
<body>
<table border="1">
    <tr><!--列-->
        <th>学号</th>
        <th>名字</th>
        <th>性别</th>
        <th>年龄</th>
        <th>籍贯</th>
        <th>操作</th>
    </tr>
    <tr th:each="student:${studentList}">
        <td th:text="${student.getId}"></td>
        <td th:text="${student.getName()}"></td>
        <td th:text="${student.getSex()}"></td>
        <td th:text="${student.getAge()}"></td>
        <td th:text="${student.getAddress()}"></td>
        <td>
            <a  role="button" th:href="@{/toupdateStudent/${student.getId()}}">修改</a>
            <a  role="button" th:href="@{/deleteStudent/${student.getId()}}">删除</a>
        </td>
    </tr>
</table>
<div >
    <a  role="button" th:href="@{/toaddStudent}">添加员工</a>
    <a  role="button" th:href="@{/toindex}">返回首页</a>
</div>
</body>
</html>

 

 

  (5) Write and modify pages 

<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<!--/*@thymesVar id="student" type="com.example.crud.pojo.Student"*/-->
<head>
    <meta charset="UTF-8">
    <title>修改页面</title>
</head>
<body>
<div >
    <form th:action="@{/updateStudent}" method="post">
        <div >
            <label >ID</label>
            <input type="text" name="id" th:value="${student.getId()}" class="form-control" placeholder="请输入该学生的id">
        </div>
        <div class="form-group">
            <label >姓名</label>
            <input type="text" name="name" th:value="${student.getName()}" class="form-control" placeholder="请输入修改后的姓名">
        </div>
        <div class="form-group">
            <label >性别</label>
            <input type="text" name="sex" th:value="${student.getSex()}" class="form-control" placeholder="请输入修改后的性别">
        </div>
        <div class="form-group">
            <label >年龄</label>
            <input type="text" name="age" th:value="${student.getAge()}" class="form-control" placeholder="请输入修改后的年龄">
        </div>
        <div class="form-group">
            <label >地址</label>
            <!--/*@thymesVar id="student" type="com.example.crud.pojo.Student"*/-->
            <input type="text" name="address" th:value="${student.getAddress()}" class="form-control" placeholder="请输入修改后的地址">
        </div>

        <button type="submit" class="btn btn-default">保存</button>
        <a role="button" th:href="@{/findStudentList}">查询员工</a>
        <a  role="button" th:href="@{/toindex}">返回首页</a>
    </form>
</div>
</body>
</html>

 screenshot

 

 (6) Write and add student information page

<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>添加页面</title>

</head>
<body>
<div  >
    <form th:action="@{/addStudent}" method="post">
        <div>
            <br>
            <label >ID</label>
            <input  type="text" name="id"  placeholder="请输入该员工的id">
        </div>

        <div>
            <label >姓名</label>
            <input type="text" name="name"  placeholder="">
        </div>

        <div>
            <label >性别</label>
            <select name="sex">
                <option value ="">null</option>
                <option value ="男">男</option>
                <option value ="女">女</option>
            </select>

        </div>

        <div>
            <label >年龄</label>
            <input type="text" name="age"  placeholder="">
        </div>

        <div>
            <label >地址</label>
            <input  type="text" name="address"  placeholder="">
        </div>

        <br>

        <button type="submit">点击添加</button>
        <a class="myButton" th:href="@{/findStudentList}">查询员工</a>
        <a class="myButton" th:href="@{/toindex}">返回首页</a>
    </form>


</div>

</body>
</html>

          This completes the project

       3. Test run

Screenshot of the successful start of the service:

 Screenshot of service failure:

 There are two solutions:

1. Modify the port number in the yml file 

2. Kill the current process on port 80

win+r enter command line input

netstat -ano

 enter

taskkill /pid 17156 -f

 

 This will continue to start the service

After the startup is complete, open the browser, enter 127.0.0.1 and press Enter

 This accesses the index.html page

 

 Click the query information to access the content of the findStudentList.html page, and display the records in the database on the page

 

Click to modify to jump to the modification page updateStudent.html

 

 Click Delete to directly delete the content in the database

Click Add to jump to the add page addStudent.html

 In this way, the writing of the CRUD instance is completed. The focus is on the part of the interaction between the Controller and the interactive front-end. There are many places worth studying. The time and energy are limited, so we cannot explain them one by one, and there are many bugs. There are many places worth optimizing. Mybatis can write better

1. The problem of concurrency control (one thread deletes the data, and another thread clicks to modify, so an error will be reported)

2. Add an empty record, and then delete the empty record (you can use a regular expression on the front-end page to solve it)

3. Add a duplicate record

        Only learning is recorded. . . . . The deficiencies still need to be criticized and corrected by the elder brother

Project source code icon-default.png?t=M85Bhttp://Link: https://pan.baidu.com/s/1oXVY-eD0ypziKzPcaKGAmg?pwd=1234 Extraction code: 1234

 

Guess you like

Origin blog.csdn.net/yvge669/article/details/127835133
Recommended