❤【爆肝万字】手把手教你SpringBoot+MyBatis+jQuery+HTML5从0开始写网页一学就会!(内附源码)❤

x33g5p2x  于2021-11-22 转载在 HTML5  
字(9.3k)|赞(0)|评价(0)|浏览(452)

今天带给大家的是SpringBoot+MyBatis+jQuery+HTML5+CSS简单实现前后端交互,保证干货满满,看完你就可以动手写你自己的程序!

首先得需要你创建一个SpringBoot项目,具体怎么创建这里久不多说啦。

其次,你的创建一张这样一张表用于连接测试功能,很简单的一张表,当然只是用于功能测试,实际业务中可没有这么简单的表哟。

创建完成以后你pom.xm文件中的中应该有如下引入依赖:

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

        <!--本地测试-->
        <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>

        <!--热部署-->
        <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依赖-->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.5.1</version>
        </dependency>

依赖写入以后,记得在点击此刻出现在你IDEA界面右上角的刷新按钮哟。

注入依赖以后,在你的项目中src目录下的resources目录下建立application.yml文件,当然你也可以使用application.properties来进行配置,但是这里我们更加推荐通过.yml文件对其进行配置,因为它的属性结构可以让参数看起来更加简洁清晰。配置如下:

spring:
  #thymeleaf页面缓存关闭
  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

# 开发环境配置
server:
  # 服务器的HTTP端口,默认为80
  port: 1717
  servlet:
    # 应用的访问路径
    context-path: /
  tomcat:
    # tomcat的URI编码
    uri-encoding: UTF-8
    # tomcat最大线程数,默认为200
    max-threads: 800
    # Tomcat启动初始化的线程数,默认值25
    min-spare-threads: 30

# 日志配置
logging:
  level:
    com.gantiexia: debug
    org.springframework: warn

# MyBatis
mybatis:
  # 搜索指定包别名
  typeAliasesPackage: com.gantiexia.**.entity
  # 配置mapper的扫描,找到所有的mapper.xml映射文件
  mapperLocations: classpath*:mapper/**/*.xml

注意! 上面spring的配置中,datasource要写入你自己数据库的连接参数,这里博主用到的MYSQL的连接方式。同样,最后MyBatis的路径配置决定了你的项目能否找到对应的承接数据库的文件。

连接数据库

在java包下创建层级目录,com/gantiexia/springboot_test,然后在springboot_test包下创建entity包,在这个包下创建实体集。

package com.gantiexia.springboot_test.entity;

/** * @author GanTieXia * @date 2021/8/21 4:20 */
public class User {
    /** 用户名*/
    private String userName;
    /** 账号*/
    private String idNumber;
    /** 密码*/
    private String passWord;
    /** 年龄*/
    private String age;
    /** 性别*/
    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 + '\'' +
                '}';
    }
}

实体集写好以后,紧接着我们在springboot_test包下创建层级目录:mapper/user,然后再在user包下创建命为UserMapper的接口:

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 {
    /** * 获取信息 * * @return */
    List<User> getMessage();
}

然后在resources目录下,创建层级目录mapper/user,在user包下面创建UserMapper.xml用于写我们的数据库查询语句。

<?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>

注意! 此处的namespace对应的是你的mapper接口所在的路径,各个namespace之间相互独立不影响。

好了,到此我们就得写个测试类看这个dao接口(又称mapper)能否连接数据库,接下来在test包下,按如下路径创建测试类,创建如下路径下的文件:

编写测试类:

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);
        }
    }
}

运行结果如下:

至此成功由代码获取到数据库中的数据。

编写业务功能模块代码

按照如下路径创建文件,注意,UserService接口在service目录下。

编写service目录下的UserService接口代码:

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 {

    /** * 获取信息 * * @return */
    List<User> getMessage();
}

编写service目录下的serviceImpl包下的UserServiceImpl类代码:

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;

    /** * 获取所有信息 * * @return */
    @Override
    public List<User> getMessage() {
        return userMapper.getMessage();
    }
}

然后创建如下层级路径以及路径下的文件:

编写controller路径下的UserCtrl文件:

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";
    }
}

接下来就要去写前端页面了,这里我们只写一个简单的样式,以供参考。

按照如下路径在resources目录下创建你的HTML5页面:

接下来我们编写testPage.html页面:

<!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;">用户名:<label id="userName"></label></p>
        </div>
        <div style="float: right">
            <p style="width: 150px;">账号:<label id="idNumber"></label></p>
        </div>
    </div>
</div>
</body>
<script type="text/javascript" src="/js/jquery-3.3.1.min.js"></script>
<script> // 这里我们随便加载一下数据,大家知道原理就好啦 $.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>

注意! 此处的中我们用到了jQuery,它的使用需要你去下载相应的js文件,放在对应的包里,这里为了大家能达到效果,建议大家将这个文件放在和我一样的路径下:

为了展示头像效果,我在static包下创建了一个picture文件夹,用来装待会我们要显示在前端的图片,你们也可以先随便放一张图片在这里,注意图片路径和图片名字得和我一样, 因为前端引入的时候输入它的路径了,你也可以在前端页面中将图片改成你自己的图片路径:

相信大家前面看了那么多遍这个文件,一定好奇这个类是干嘛的吧!

他就是我们springBoot项目中的启动类啦,这个文件我是放在gantiexia这个文件的路径下面的, 因为它能够读取到同级以及同级子目录下的文件。这样无论你是由多少个包像springboot_test、springboot_testOne、springboot_testThree等等等它都能识别到。我们来看看它长什么样子:

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项目启动成功...");
    }

}

当然我自己改动了一下的哈。我们找到这个类,右键运行起这个类:

在访问前端网页的时候,要确保你的数据库能够正常连接。

接下来我们打开网页,输入刚才我们控制器中定义的url地址,端口号为我们application.yml文件中server下定义的port: 1717(可随意更改,只要不冲突就好)。注意这里我们前端页面Ajax中取得是数据库中得第一条数据没加任何得业务逻辑。

输入网址:localhost:1717/firstTest/testMyFirstPage

效果图:

到此,数据库-后端-前端全部打通,如果有不懂的,欢迎大家留言,我会一一解答。

今天的分享就到这里,觉得博主的分享有用的记得一键三连,谢谢大家,我们下期再见~

相关文章

微信公众号

最新文章

更多