手把手教你基于SpringBoot+Mybatis+Redis搭建简单的web服务-4

209 阅读1分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第19天,点击查看活动详情

1.12 启动项目

在地址栏中输入localhost:8084/quseryUserList ,出现数据库表中的信息即为成功。这是第一个查询User表所有的数据,其他CRUD方法输入相应地址即可。 image9.png

2. 使用springboot+mybatis+thymeleaf+html展示一张数据库表

注:需要在1.的基础上修改项目

2.1 在pom.xml里添加thymeleaf依赖

在1.中已经添加过了,这里不再叙述

2.2 在application.yml里添加thymeleaf配置

spring:
  thymeleaf:
    prefix: "classpath:/templates/"
    suffix: ".html"

2.3 创建html文件

在resources文件夹下添加templates文件夹,在templates文件夹下创建items.html文件 用于写前端代码。 image10.png

2.4 添加前端代码

在tiems.html里写前端页面代码如下 ,html用法可去百度查询,参数说明:userList 是后端传递过来的参数

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>springboot</title>
</head>
<body>
<table border="1">
    <tr th:each="item : ${userList}">
        <td th:text="${{item.id}}"></td>
        <td th:text="${{item.name}}"></td>
        <td th:text="${{item.pwd}}"></td>
    </tr>
</table>

</body>
</html>

2.5 创建ThymeleafUserController

在controller 文件夹下创建 ThymeleafUserController.java 代码如下 ( 1.Model 为与前端交互的API,将查询出来的userList 传给前端。2.return 要写"items.html",否则会出错,3.注意要写@Controller ,不能写RestController 否则无法返回正确的页面)

package com.example.myFirstBlog.controller;

import com.example.myFirstBlog.entity.User;
import com.example.myFirstBlog.mapper.UserMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@Controller
public class ThymeleafUserController {
    @Resource
    private UserMapper userMapper;

    @RequestMapping("/user")
    public String toShowUser(Model model){
        List<User> userList = userMapper.queryUserList();
        model.addAttribute("userList",userList);
        return "items.html";
    }
}

2.6 重新启动项目

在地址栏输入 localhost:8084/user image11.png