我是靠谱客的博主 现实鸭子,最近开发中收集的这篇文章主要介绍Springboot+mybatis用Ajax+thymeleaf实现前端操作用户信息表并分页显示相关数据的功能一、微读理论知识,实现功能所要的文件资源:,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

一、微读理论知识,实现功能所要的文件资源:

Ajax 全称是“Asynchronous Javascript And XML”(异步 JavaScript和 XML),是指一种创建交互式、快速动态网页应用的网页开发技术,无需重新加载整个网页的情况下,能够更新部分网页的技术。Ajax利用javascript代替传统的表单提交方式,和服务器进行少量数据交换。可以将响应信息利用javascript进行网页数据的部分更新。AJAX涉及到7项技术,Javascript、XMLHttpRequest、Dom、css、HTML、XML以及相关服务器API。

GroupId和ArtifactId被统称为“坐标”是为了保证项目唯一性而提出的。

——引自百度百科

在thymeleaf中使用Axios请求:需要在script标签里导入文件

<script th:src="@{/js/axios.min.js}"></script>

axios.min.js 提取码: 123m 

更多Axios.js资源链接

axios.min.js-资源下载(axios-0.27.2版本)---百度网盘_CN丶1的博客-CSDN博客

二、创建项目(initializr+web+mysql+mybatis)

项目工程名称为自己定

包com下再建包work, 即com.work

具体步骤见下列各图:

1、在线使用Spring Initializr创建项目

2、项目类型Type选择Maven,因为是安装jdk1.8,所以Java Version选8,Package是com.work

3、点击Web,勾选Spring Web;点击Template Engines,勾选Thymeleaf;点击SQL,勾选Mybatis FrameWork和MySQL Driver。

4、更改项目名称和存放路径(任意,合理即可)

5、项目的结构如下:

三、引入相关依赖

完整依赖:(严格根据上述新建工程的步骤完成至此,pom.xml文件可完全采用以下的代码,但是要注意java的版本,这里我使用的是jdk1.8)

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.work</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--mybatis分页技术依赖-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.12</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>

    <build>
        <!-- 如果不添加此节点mybatis的mapper.xml文件、yaml、html等文件都会被漏掉。要用过滤器过滤.html等资源文件,以保证它们不会被漏掉。-->
        <resources>
            <resource>
                    <directory>src/main/resources</directory>
                    <includes>
                        <include>**/*.properties</include>
                        <include>**/*.xml</include>
                        <include>**/*.html</include>
                        <include>**/*.yaml</include>
                    </includes>
                    <filtering>true</filtering>
                </resource>

                <resource>
                    <directory>src/main/java</directory>
                    <includes>
                        <include>**/*.properties</include>
                        <include>**/*.xml</include>
                        <include>**/*.html</include>
                        <include>**/*.yaml</include>
                    </includes>
                    <filtering>true</filtering>
                </resource>
            </resources>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

相关依赖配置解释:

前端的模板引擎:

<dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-thymeleaf</artifactId>

</dependency>

mybatis分页插件:

<dependency>

            <groupId>com.github.pagehelper</groupId>

            <artifactId>pagehelper-spring-boot-starter</artifactId>

            <version>1.2.12</version>

            <scope>compile</scope>

</dependency>

配置分页插件,两种方式:

  1. MyBatis的核心配置文件中配置插件在pom.xml中引入以下代码出错的话则才用配置文件application.yaml的方式,下面的第2点
<build>

<plugins>

<!--设置分页插件-->

<plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>

</plugins>

</build>
  1. 在springboot配置文件(application.yaml)中声明插件完成本功能的yaml完整代码见下面的第三点,即 第三、配置资源文件
#pagehelper分页插件配置

pagehelper:

  helperDialect: mysql

  reasonable: true

  supportMethodsArguments: true

  params: count=countSql

四、配置资源文件

Properties文件配置

server.servlet.encoding.charset=utf-8
server.servlet.encoding.force=true
server.servlet.encoding.enabled=true

YAML文件写入thymeleaf的配置application.yaml)

server:
  port: 8080
spring:
  thymeleaf:
    enabled: true  #开启thymeleaf视图解析
    encoding: utf-8  #编码
    prefix: classpath:/templates/    #thymeleaf翻译页面路径
    cache: false      #是否使用缓存
    mode: HTML      #严格的HTML语法模式
    suffix: .html   #后缀名
  datasource:
    driverClassName: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/ajax_test?serverTimezone=UTC&useSSL=true&characterEncoding=UTF-8
    username: root #(自己的数据库服务用户名,link的名称)
    password: ****** #按照实际情况(自己的数据库密码)。
    maxActive: 50
    maxWait: 2000
    minIdle: 10
mybatis:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  type-aliases-package: com.work.domain
  #配置MyBatis的XML配置文件路径
  mapper-locations:
    classpath*:com/work/mapper/**/*.xml
pagehelper:
  helperDialect: mysql
  reasonable: true
  supportMethodsArguments: true
  params: count=countSql

五、数据库创建

1、创建名字为ajax_test的数据库

2、新建数据库表t_user

六、在domain包下创建实体类

User.java

package com.work.domain;

public class User {
    private int id;
    private String name;
    private String password;
    private String birthday;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getBirthday() {
        return birthday;
    }

    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "User{" +
                ", id='" + id + ''' +
                ", name='" + name + ''' +
                ", password='" + password + ''' +
                ", birthday='"+birthday+'''+
                '}';
    }

}

七、在mapper包和service包(数据操作接口、服务层)中进行数据的增删改查

mapper包

1、创建UserMapper接口

UserMapper.interface接口代码:

package com.work.mapper;

import com.work.domain.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface UserMapper {
    @Select("SELECT * FROM t_user")
    public List<User> findAll();
    //根据用户名查询用户
    @Select("SELECT * From t_user where name = #{name}")
    public List<User> findByName(String name);
    //根据用户id删除用户
    @Delete("DELETE FROM t_user where id = #{id}")
    public int delUser(int id);
    //添加用户
    int addUser(User user);
    //根据用户id更新用户密码
    @Update("UPDATE t_user SET password=#{password} where id=#{id}")
    public int updateUser(int id,String password);
    //根据用户id查询用户信息
    @Select("SELECT * From t_user where id = #{id}")
    public User findById(int id);
}

2、创建UserMapper.xml文件

新建一个普通的File文件,后缀名是.xml,便可新建一个.xml文件。

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.work.mapper.UserMapper">
    <insert id="addUser" keyProperty="id" useGeneratedKeys="true" parameterType="com.work.domain.User">
        insert into t_user(name,password,birthday) values(#{name},#{password},#{birthday})
    </insert>
</mapper>

service包

UserService.interface接口代码:

package com.work.service;

import com.github.pagehelper.PageInfo;
import com.work.domain.User;
import java.util.List;

public interface UserService {
    List<User> findAll();
    //根据用户名查询用户
    List<User> findByName(String name);
    //根据用户id删除用户
    int delUser(int id);
    //根据用户id更新用户密码
    int updateUser(int id,String password);
    //根据用户id查询用户信息
    User findById(int id);
    //根据页码和页面大小创建分页的接口函数
    public PageInfo<User> PageUser(Integer pageNum, Integer pageSize);
    int addUser(User user);
}



UserServiceImpl实现类代码:

package com.work.servletComponent;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.work.domain.User;
import com.work.mapper.UserMapper;
import com.work.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    @Cacheable(cacheNames = "findAll")
    public List<User> findAll() {
        return userMapper.findAll();
    }
    @Override
    public List<User> findByName(String name){return userMapper.findByName(name);}
    @Override
    @Cacheable(cacheNames = "delUser")
    public int delUser(int id){
        return userMapper.delUser(id);
    }
    @Override
    public int addUser(User user){
        return userMapper.addUser(user);
    }
    @Override
    public int updateUser(int id,String password){
        return userMapper.updateUser(id,password);
    }
    @Override
    public User findById(int id){
        return userMapper.findById(id);
    }
    @Override
    public PageInfo<User> PageUser(Integer pageNum, Integer pageSize){
//开启分页
        PageHelper.startPage(pageNum,pageSize);
        List<User> userList = userMapper.findAll();
        PageInfo<User> pageInfo = new PageInfo<>(userList);
        return pageInfo;
    }
}

八、controller控制层与时间处理类

UserController控制器类代码:

package com.work.controller;
import com.github.pagehelper.PageInfo;
import com.work.domain.User;
import com.work.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller

@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("check")
    @ResponseBody
    public String checkName(String name) {
        List<User> u = userService.findByName(name);
        if (u.size() == 0) {
            return "yes";
        } else {
            return "no";
        }
    }

    @RequestMapping("findAll")
    public String findAllUser(Model model, @RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                              @RequestParam(value = "pageSize", defaultValue = "3") int pageSize) {
        PageInfo<User> pageInfo = userService.PageUser(pageNo, pageSize);
        List<User> list = pageInfo.getList();
        int page = pageInfo.getPages();
        model.addAttribute("userList", list);
        model.addAttribute("pages", page);
        return "Register";
    }

    @RequestMapping("changePageSize")
    @ResponseBody
    public PageInfo<User> drop(@RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                               @RequestParam(value = "pageSize", defaultValue = "3") int pageSize) {
        PageInfo<User> pageInfo = userService.PageUser(pageNo, pageSize);
        return pageInfo;
    }

    @RequestMapping("change")
    @ResponseBody
    public List<User> change(@RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                             @RequestParam(value = "pageSize", defaultValue = "3") int pageSize) {
        PageInfo<User> pageInfo = userService.PageUser(pageNo, pageSize);
        List<User> list = pageInfo.getList();
        return list;
    }

    @RequestMapping("del")
    public String delById(@RequestParam("userId") Integer id) {
        userService.delUser(id);
        return "redirect:/user/findAll";
    }

    @RequestMapping("add")
    public String addUser(@RequestParam("name")String name,@RequestParam("password")String password,@RequestParam("birthday") String birthday) {
        User user = new User();
        user.setName(name);
        user.setPassword(password);
        user.setBirthday(birthday);
        userService.addUser(user);
        return "redirect:/user/findAll";
    }
    @RequestMapping("add.html")
    public String findaddPage(){
        return "add";
    }

    @RequestMapping("update")
    public String updateUser(@RequestParam("id")int id, @RequestParam("password") String password, Model model) {
        userService.updateUser(id, password);
        return "redirect:/user/findAll";
    }

    @RequestMapping("findById")
    public String select(Model model, int userId) {
        User user = userService.findById(userId);
        model.addAttribute("users", user);
        model.addAttribute("userId",userId);
        return "/update";
    }
}

九、前端模板HTML文件

Register.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户信息展示页面</title>
    <script th:src="@{/js/axios.min.js}"></script>
</head>
<body>
<table border="1">
    <thead>
    <tr>
        <th>编号</th>
        <th>姓名</th>
        <th>密码</th>
        <th>生日</th>
        <th>删除</th>
        <th>修改</th>
    </tr>
    </thead>
    <tbody id="users">
    <tr th:each="u: ${userList}">
        <td th:text="${u.id}"></td>
        <td th:text="${u.name}"></td>
        <td th:text="${u.password}"></td>
        <td th:text="${u.birthday}"></td>
        <td><a th:href="@{/user/del(userId=${u.id})}">删除</a></td>
        <td><a th:href="@{/user/findById(userId=${u.id})}">修改</a>
        </td>
    </tr>
    </tbody>
</table>

<form action="/user/findAll" method="get">
    每页显示数据:
    <select name="pageSize" onchange="get(this.value)" id="reset">
        <option value=3>3条</option>
        <option value=5>5条</option>
        <option value=7>7条</option>
    </select>
    页码:<span id="aSpan"><a th:each="i:${#numbers.sequence(1,pages)}" th:text="${i}"
                           th:href="@{/user/findAll(pageNo=${i})}" style="margin-left: 13px"></a></span>
</form>
<a th:href="@{/user/add.html}">添加</a>
<script>
    function get(value){
        let obj = document.getElementById("reset")
        console.log(obj.value)
        axios.get("/user/changePageSize",{
            params: {
                pageSize:value
            }
        }).then(response=>{
            let body = document.getElementById("users");
            let str = ``;
        for (let user of response.data.list) {
            str+=`<tr>
                    <td>${user.id}</td>
                    <td>${user.name}</td>
                    <td>${user.password}</td>
                    <td>${user.birthday}</td>
                    <td><a href="/user/del?userId=${user.id}">删除</a></td>
                    <td><a href="/user/findById?userId=${user.id}">修改</a></td>
               </tr>`
        }
        body.innerHTML=str

        let key = response.data.pages
        let a = document.getElementById("aSpan")
        let str2 =``;
        for (let i = 1; i <= key; i++) {
            str2 += `<a href="javascript:page(${i},${response.data.list.length})" style='margin-left: 10px'>${i}</a>`
        }
        a.innerHTML = str2;
    })
    }
    function page(num,size){
        let obj = document.getElementById("aSpan")
        axios.get(`/user/change`,{
            params:{
                pageSize:size,
                pageNo:num
            }
        }).then(response =>{
            let body = document.getElementById("users")
            let str ='';
        for (let user of response.data) {
            str+=`<tr>
                    <td>${user.id}</td>
                    <td>${user.name}</td>
                    <td>${user.password}</td>
                    <td>${user.birthday}</td>
                    <td><a href="/user/del?userId=${user.id}">删除</a></td>
                    <td><a href="/user/findById?userId=${user.id}">修改</a></td>
               </tr>`
        }
        body.innerHTML=str
    })
    }
</script>
</body>
</html>

注:其中的``是反引号,作用是可以格式化字符串。

update.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>update</title>
</head>
<body>
<form action="/user/update" method="post">
    编号:<input type="text" name="id" th:value="${userId}"><br>
    姓名:<input type="text" name="name" th:value="${name}" readonly><br>
    密码:<input type="text" name="password" th:value="${password}"><br>
    生日:<input type="text" name="birthday" th:value="${birthday}" readonly><br>
    <input type="submit" value="提交">
</form>
</body>
</html>

add.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Title</title>
    <script th:src="@{/js/axios.min.js}"></script>
</head>
<body>
<form action="/user/add" method="get">
    用户名: <input type="text" id="name" name="name" onblur="checkName()" value=""><span id="one"></span><br>
    密码: <input type="password" name="password"><br>
    生日: <input type="date" name="birthday"><br>
    <input type="submit" id="add" value="添加" >
</form>
<script>
    function checkName() {
        let obj = document.getElementById("name");
        let param = new URLSearchParams();
        let span = document.getElementById("one");
        let addObj = document.getElementById("add");
        param.append("name", obj.value)
        axios.post('/user/check', param).then(response => {
            console.log(response)
            param.append("name", obj.value)
            if (response.data == 'no') {
            span.innerText = "用户名重复";
            addObj.disabled=true;
        } else {
            span.innerText = "";
            addObj.disabled=false;
        }
    })}
</script>
</body>
</html>

十、代码可能出现报错的情况及其解决方法

出现let关键字报错的情况,解决方法如下:

Idea编辑器左上角菜单

File--->Settings--->Languages Frameworks--->JavaScript--->选择ECMAScript 6

十一、至此,与本功能相关的代码和文件的配置已全部完成,可以运行主类了。运行结果如下:

 

正在上传…重新上传取消正在上传…重新上传取消

注:修改页面只做了根据id修改密码的功能。

 

谢谢^V^

最后

以上就是现实鸭子为你收集整理的Springboot+mybatis用Ajax+thymeleaf实现前端操作用户信息表并分页显示相关数据的功能一、微读理论知识,实现功能所要的文件资源:的全部内容,希望文章能够帮你解决Springboot+mybatis用Ajax+thymeleaf实现前端操作用户信息表并分页显示相关数据的功能一、微读理论知识,实现功能所要的文件资源:所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(38)

评论列表共有 0 条评论

立即
投稿
返回
顶部