❤❤[Let's talk about SpringBoot+MyBatis+jQuery+HTML5 and start writing web pages from 0!Included Source Code)❤❤

Today we're bringing you SpringBoot+MyBatis+jQuery+HTML5+CSS for simple front-end and back-end interaction, so you can write your own program after you've finished!

First, you need to create a SpringBoot project. It won't be long before you know exactly how to create it.

Secondly, you create a table like this to connect test functions, a very simple table, of course, only for function testing. There are no such simple tables in actual business.

Once created, you should have the following dependencies in your pom.xm file:

        <!--springWeb-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--Local Test-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>

        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>5.1.38</scope>
        </dependency>

        <!--Hot Deployment-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>

        <!--thymeleaf-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <!--jquery rely on-->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.5.1</version>
        </dependency>

After writing dependencies, remember to click the refresh button that appears at the top right corner of your IDEA interface at this time.


After injecting dependencies, create an application.yml file in the resources directory in the src directory of your project, and of course you can configure it using application.properties, but here we recommend configuring it using the.Yml file, because its attribute structure makes the parameters look simpler and clearer.The configuration is as follows:

spring:
  #thymeleaf page cache shutdown
  thymeleaf:
    cache: false
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
    driver-class-name: com.mysql.cj.jdbc.Driver


# Development Environment Configuration
server:
  # HTTP port of the server, default to 80
  port: 1717
  servlet:
    # Application Access Path
    context-path: /
  tomcat:
    # URI encoding for tomcat
    uri-encoding: UTF-8
    # Maximum number of tomcat threads, default to 200
    max-threads: 800
    # Number of threads initialized by Tomcat startup, default 25
    min-spare-threads: 30

# Log Configuration
logging:
  level:
    com.gantiexia: debug
    org.springframework: warn

# MyBatis
mybatis:
  # Search for specified package aliases
  typeAliasesPackage: com.gantiexia.**.entity
  # Configure mapper's scan to find all mapper.xml mapping files
  mapperLocations: classpath*:mapper/**/*.xml

Be careful!In the configuration of spring above, datasource writes the connection parameters of your own database, the connection mode of MYSQL used by the blogger here.Similarly, the final path configuration for MyBatis determines whether your project can find the file that will host the database.

Connect to database

Create a hierarchical directory under the java package, com/gantiexia/springboot_test, then springboot_Create entity packages under the test package, under which entity sets are created.

package com.gantiexia.springboot_test.entity;

/**
 * @author GanTieXia
 * @date 2021/8/21 4:20
 */
public class User {
    /** User name*/
    private String userName;
    /** Account number*/
    private String idNumber;
    /** Password*/
    private String passWord;
    /** Age*/
    private String age;
    /** Gender*/
    private String sex;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getIdNumber() {
        return idNumber;
    }

    public void setIdNumber(String idNumber) {
        this.idNumber = idNumber;
    }

    public String getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "User{" +
                "userName='" + userName + '\'' +
                ", idNumber='" + idNumber + '\'' +
                ", passWord='" + passWord + '\'' +
                ", age='" + age + '\'' +
                ", sex='" + sex + '\'' +
                '}';
    }
}

When the entity set is written, we start at springboot_Create a hierarchical directory under the test package: mapper/user, then create an interface named UserMapper under the user package:

package com.gantiexia.springboot_test.mapper.user;

import com.gantiexia.springboot_test.entity.User;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

/**
 * @author GanTieXia
 * @date 2021/8/21 4:30
 */
@Mapper
public interface UserMapper {
    /**
     * pick up information
     *
     * @return
     */
    List<User> getMessage();
}

Then under the resources directory, create a hierarchical directory, mapper/user, and under the user package, create UserMapper.xml to write our database query statements.

<?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.gantiexia.springboot_test.mapper.user.UserMapper">
    
    <select id="getMessage" resultType="com.gantiexia.springboot_test.entity.User">
        select userName,idNumber,passWord,age,sex from t_user;
    </select>

</mapper>

Be careful!The namespace here corresponds to the path of your mapper interface, and each namespace is independent of each other.

Okay, so here we have to write a test class to see if this dao interface (also known as mapper) can connect to the database. Next, under the test package, create a test class by following the path below, and create a file under the following path:

Write test classes:

package com.gantiexia.springboot_test;

import com.gantiexia.springboot_test.entity.User;
import com.gantiexia.springboot_test.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
class SpringbootUserCtrlApplicationTests {

    @Autowired
    private UserService userService;

    @Test
    public void getAllMessage(){
        List<User> list = userService.getMessage();
        for(User user : list){
            System.out.println(user);
        }
    }
}

The results are as follows:

The data in the database was successfully retrieved from the code.

Write business module code

Follow the path below to create the file, noting that the UserService interface is in the service directory.

Write the UserService interface code in the service directory:

package com.gantiexia.springboot_test.service;

import com.gantiexia.springboot_test.entity.User;

import java.util.List;

/**
 * @author GanTieXia
 * @date 2021/8/21 4:36
 */
public interface UserService {

    /**
     * pick up information
     *
     * @return
     */
    List<User> getMessage();
}

Write the UserServiceImpl class code under the serviceImpl package in the service directory:

package com.gantiexia.springboot_test.service.serviceImpl;

import com.gantiexia.springboot_test.entity.User;
import com.gantiexia.springboot_test.mapper.user.UserMapper;
import com.gantiexia.springboot_test.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author GanTieXia
 * @date 2021/8/21 4:36
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * Get all the information
     *
     * @return
     */
    @Override
    public List<User> getMessage() {
        return userMapper.getMessage();
    }
}

Then create the following hierarchical paths and files under them:

Write the UserCtrl file under the controller path:

package com.gantiexia.springboot_test.controller;

import com.gantiexia.springboot_test.entity.User;
import com.gantiexia.springboot_test.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author GanTieXia
 * @date 2021/8/20 23:06
 */
@Controller
@RequestMapping("firstTest")
public class UserCtrl {

    @Autowired
    private UserService userService;

    @RequestMapping("/getMessage")
    @ResponseBody
    public List<User> getMessage(){
        return userService.getMessage();
    }

    @RequestMapping("/testMyFirstPage")
    public String toPage(){
        return "/user/testPage";
    }
}

Now we're going to write the front-end page. Here we'll just write a simple style for reference.

Create your HTML5 page in the resources directory as follows:

Next, we write the testPage.html page:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>SpringBoot</title>
</head>
<style>
    #picture {
        width: 50px;
        height: 50px;
        border-radius: 50%;
        background-color: red;
        position: relative;
        left: -25px;
    }
    #showPicture{
        width: 50px;
        height: 50px;
        border-radius: 50%;
    }
</style>
<body>
<div>
    <div style="width: 100%;background-color: cornflowerblue;height: 50px">
        <div id="picture" style="float: right;">
            <img id="showPicture" src="/picture/picture.jpg">
        </div>
        <div style="float: right">
            <p style="width: 150px;">User name:<label id="userName"></label></p>
        </div>
        <div style="float: right">
            <p style="width: 150px;">Account number:<label id="idNumber"></label></p>
        </div>
    </div>
</div>
</body>
<script type="text/javascript" src="/js/jquery-3.3.1.min.js"></script>
<script>
    // Let's just load the data here and you know how it works
    $.ajax({
        type:"post",
        url: "/firstTest/getMessage",
        async:false,
        success:function (data) {
            for(var i=0;i<data.length;i++){
                $("#userName").html(data[0].userName)
                $("#idNumber").html(data[0].idNumber)
            }

        }
    })
</script>
</html>

Be careful!Here we use jQuery, which requires you to download the corresponding js file and put it in the corresponding package. For you to achieve the effect, we recommend that you put this file in the same path as me:

To show the avatar effect, I created a picture folder under the static package to hold the pictures we want to show on the front end. You can also put a picture here first. Note that the picture path and picture name have to be the same as mine, because when the front end is introduced, enter its path.You can also change the picture to your own picture path in the front-end page:

I believe you have read this file so many times before, you must be curious what this kind of file is for.

He's the startup class in our springBoot project. I put this file under the path of the gantiexia file because it can read files from its siblings and subdirectories.So no matter how many packages you have like springboot_test, springboot_testOne, springboot_testThree, and so on. It recognizes it.Let's see what it looks like:

package com.gantiexia;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author GanTieXia
 * @date 2021/8/20 23:06
 */
@SpringBootApplication
public class SpringbootTestApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootTestApplication.class, args);
        System.out.println("springBoot Project started successfully...");
    }

}

Of course I changed it myself.We found this class and right-click to run it:

When accessing front-end web pages, make sure your database is properly connected.

Next, we open the web page and enter the url address we just defined in our controller. The port number is port: 1717 defined under server in our application.yml file (you can change it as you like, as long as it doesn't conflict).Note here that the first data we get in the database from our front-end page, Ajax, does not add any business logic.

Enter the web address: localhost:1717/firstTest/testMyFirstPage

Design sketch:

At this point, the database - back-end - front-end all work, if you do not understand, you are welcome to leave a message, I will answer one by one.

That's all for today's sharing. I feel that the blogger's sharing is worth remembering one click, three times. Thank you, we'll see you next time.

Tags: html5 JQuery Spring Boot css Ajax

Posted on Tue, 07 Sep 2021 23:00:46 -0400 by FarhanKhalaf