基于SpringBoot和Mybatis实现的留言板案例

目录

一、需求及界面展示

二、准备工作

引入依赖

.yml文件相关配置

数据库数据准备

三、编写后端代码

需求分析

代码结构

Model

Mapper

Service

Controller

前端代码

四、测试


一、需求及界面展示

需求:

1. 输入留言信息,点击提交,后端把数据存储起来

2. 页面展示输入的留言板信息

二、准备工作

引入依赖

.yml文件相关配置

XML 复制代码
spring:
  application:
    name: messageboard-demo
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/mybatis_test?characterEncoding=utf8&useSSL=false
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver

mybatis:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 配置打印 MyBatis 执行的 SQL
    map-underscore-to-camel-case: true  #配置自动驼峰转换

数据库相关配置,需要改成自己的数据库名和数据库用户名密码

数据库数据准备

我这里使用的数据库是mybatis_test

sql 复制代码
create database mybatis_test;

use mybatis_test;

DROP TABLE IF EXISTS message_info;
CREATE TABLE `message_info` (
                                `id` INT ( 11 ) NOT NULL AUTO_INCREMENT,
                                `from` VARCHAR ( 127 ) NOT NULL,
                                `to` VARCHAR ( 127 ) NOT NULL,
                                `message` VARCHAR ( 256 ) NOT NULL,
                                `delete_flag` TINYINT ( 4 ) DEFAULT 0 COMMENT '0-正常, 1-删除',
                                `create_time` DATETIME DEFAULT now(),
                                `update_time` DATETIME DEFAULT now() ON UPDATE now(),
                                PRIMARY KEY ( `id` )
) ENGINE = INNODB DEFAULT CHARSET = utf8mb4;

update_time字段中 ON UPDATE now(),表示当数据发生更新操作时,自动把该列的值设置为now(),now()可以替换成其他获取时间的标识符,比如:CURRENT_TIMESTAMP(),LOCALTIME()等。MySQL5.6.5以上版本和5.6.5以下版本会有一些区别。

三、编写后端代码

需求分析

后端需要提供两个服务:

  1. 提交留言:用户输入留言信息之后,后端需要把留言信息保存起来

  2. 展示留言:页面展示时,需要从后端获取到所有的留言信息

代码结构

Model

java 复制代码
import lombok.Data;

import java.util.Date;

@Data
public class MessageInfo {
    private Integer id;
    private String from;
    private String to;
    private String message;
    private Integer deleteFlag;
    private Date createTime;
    private Date updateTime;
}

Mapper

java 复制代码
import cn.hxxy.messageboard.model.MessageInfo;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface MessageInfoMapper {

    @Select("select `from`, `to`, `message` from message_info where delete_flag = 0")
    List<MessageInfo> queryAll();

    @Insert("insert into message_info (`from`, `to`, `message`) values (#{from}, #{to}, #{message})")
    Integer insertMessage(MessageInfo messageInfo);
}

insert语句中,from和to属于MySQL关键字,必须加上反引号.

Service

java 复制代码
import cn.hxxy.messageboard.mapper.MessageInfoMapper;
import cn.hxxy.messageboard.model.MessageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MessageService {

    @Autowired
    private MessageInfoMapper messageInfoMapper;

    public Integer publish(MessageInfo messageInfo) {
        return messageInfoMapper.insertMessage(messageInfo);
    }

    public List<MessageInfo> getList() {
        return messageInfoMapper.queryAll();
    }
}

Controller

java 复制代码
import cn.hxxy.messageboard.model.MessageInfo;
import cn.hxxy.messageboard.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/message")
public class MessageController {

    @Autowired
    private MessageService messageService;

    @RequestMapping("/publish")
    public boolean publish(MessageInfo messageInfo) {
        //参数合法性校验
        if (!StringUtils.hasLength(messageInfo.getFrom()) ||
                !StringUtils.hasLength(messageInfo.getTo()) ||
                !StringUtils.hasLength(messageInfo.getMessage())) {
            return false;
        }
        Integer result = messageService.publish(messageInfo);
        return result != 0; //插入成功,返回true
    }

    @RequestMapping("/getList")
    public List<MessageInfo> getList() {
        return messageService.getList();
    }
}

前端代码

html 复制代码
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>留言板</title>
    <style>
        .container {
            width: 350px;
            height: 300px;
            margin: 0 auto;
            /* border: 1px black solid; */
            text-align: center;
        }

        .grey {
            color: grey;
        }

        .container .row {
            width: 350px;
            height: 40px;

            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .container .row input {
            width: 260px;
            height: 30px;
        }

        #submit {
            width: 350px;
            height: 40px;
            background-color: orange;
            color: white;
            border: none;
            margin: 10px;
            border-radius: 5px;
            font-size: 20px;
        }
    </style>
</head>

<body>
<div class="container">
    <h1>留言板</h1>
    <p class="grey">输入后点击提交, 会将信息显示下方空白处</p>
    <div class="row">
        <span>谁:</span> <input type="text" name="" id="from">
    </div>
    <div class="row">
        <span>对谁:</span> <input type="text" name="" id="to">
    </div>
    <div class="row">
        <span>说什么:</span> <input type="text" name="" id="say">
    </div>
    <input type="button" value="提交" id="submit" onclick="submit()">
    <!-- <div>A 对 B 说: hello</div> -->
</div>

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
    //加载页面时就读取列表信息并展示
    $.ajax({
        url: "/message/getList",
        type: "get",
        success: function (MessageInfoList) {
            //展示列表内容
            var data = "";
            for (var messageInfo of MessageInfoList) {
                data += "<div>" + messageInfo.from + "对" +
                    messageInfo.to + "说: " + messageInfo.message + "</div>";
            }
            $(".container").append(data);
        }
    });

    //点击提交按钮进行的处理
    function submit() {
        //1. 获取留言的内容
        var from = $('#from').val();
        var to = $('#to').val();
        var say = $('#say').val();
        if (from === '' || to === '' || say === '') {
            alert("请将输入框填完整")
            return;
        }
        //内容合法,使用Ajax发起请求
        $.ajax({
            url: "/message/publish",
            type: "post",
            data: {
                from: from, //from: $("#from").val(),
                to: to,     //to: $("#to").val(),
                message: say    //say: $("#say").val(),
            },
            success: (function (result) {
                if (result) {
                    //信息格式正确,页面要展示数据
                    //2. 构造节点
                    var divE = "<div>" + from + "对" + to + "说: " + say + "</div>";
                    //3. 把节点添加到页面上
                    $(".container").append(divE);
                    //4. 清空输入框的值
                    $('#from').val("");
                    $('#to').val("");
                    $('#say').val("");
                } else {
                    //格式错误
                    alert("输入数据不合法")
                }
            })
        });
    }

</script>
</body>

</html>

前端主要看script标签内的代码,里面使用了jQuery和Ajax,通过GET请求从服务器获取消息列表,并将其展示在名为"container"的容器中。定义了一个名为"submit"的函数,该函数在点击提交按钮时被调用,它从输入框中获取留言内容,并通过POST请求将留言发布到服务器。如果留言格式正确,它会将留言内容添加到页面上,并清空输入框的值;如果留言格式错误,它会弹出一个警告框。

请注意,这段代码依赖于引入jQuery库,因此需要在HTML文件中添加以下代码:

html 复制代码
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script>

四、测试

运行程序,访问 http://127.0.0.1:8080/messagewall.html

数据库已有信息会直接展示

输入留言信息,点击提交,发现页面列表展示新的数据,并且数据库也添加了一条记录

重启服务,页面展示不变

相关推荐
哎呦没30 分钟前
大学生就业招聘:Spring Boot系统的架构分析
java·spring boot·后端
编程、小哥哥1 小时前
netty之Netty与SpringBoot整合
java·spring boot·spring
IT学长编程2 小时前
计算机毕业设计 玩具租赁系统的设计与实现 Java实战项目 附源码+文档+视频讲解
java·spring boot·毕业设计·课程设计·毕业论文·计算机毕业设计选题·玩具租赁系统
莹雨潇潇2 小时前
Docker 快速入门(Ubuntu版)
java·前端·docker·容器
杨哥带你写代码2 小时前
足球青训俱乐部管理:Spring Boot技术驱动
java·spring boot·后端
郭二哈3 小时前
C++——模板进阶、继承
java·服务器·c++
A尘埃3 小时前
SpringBoot的数据访问
java·spring boot·后端
yang-23073 小时前
端口冲突的解决方案以及SpringBoot自动检测可用端口demo
java·spring boot·后端
沉登c3 小时前
幂等性接口实现
java·rpc
代码之光_19803 小时前
SpringBoot校园资料分享平台:设计与实现
java·spring boot·后端