目錄
1. 添加依賴
2. 配置數據庫
2.1 創建數據庫與數據表
2.2 創建與數據庫對應的實體類
3. 后端代碼
3.1 目錄結構
3.2?MessageController類
3.3?MessageService類
3.4?MessageMapper接口
4. 前端代碼
5. 單元測試
5.1?后端接口測試
5.2 使用前端頁面測試
在Spring專欄中,已經實現了Spring MVC版的留言墻,詳見下文:
【SpringMVC】_SpringMVC實現留言墻_使用springmvc完成一個簡單的留言板-CSDN博客文章瀏覽閱讀994次,點贊24次,收藏17次。1、請求:/message/publish2、參數:使用對象MessageInfo進行存儲參數:3、響應:true/false;_使用springmvc完成一個簡單的留言板https://blog.csdn.net/m0_63299495/article/details/139359758該版本的消息存儲采用了List<MessageInfo>存儲,每次重啟服務器就會導致信息丟失。
本文基于上文,對表白墻系統進行持久化。
1. 添加依賴
在pom.xml文件中使用Alt+insert快捷鍵,在EditStarters中選擇MyBatis與Mysql的相關依賴:
并在maven面板中進行刷新;
2. 配置數據庫
2.1 創建數據庫與數據表
創建數據庫,名為message:
在該庫下創建messgae_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;
在application.yml中進行數據庫與MyBatis的相關配置:
# 端口配置
server:port: 8080
# 數據庫連接配置
spring:datasource:url: jdbc:mysql://127.0.0.1:3306/message?characterEncoding=utf8&useSSL=falseusername: rootpassword: xxxxxxdriver-class-name: com.mysql.cj.jdbc.Driver
mybatis:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #配置打印MyBatis日志map-underscore-to-camel-case: true #配置轉換駝峰
2.2 創建與數據庫對應的實體類
修改MessageInfo類,增加id、deleteFlag、createTime、uodateTime屬性與數據表字段對應:
package com.example.springbootdemo2.controller;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;
}
3. 后端代碼
3.1 目錄結構
創建controller、service、mapper、model包,并創建對應類或接口:
其中,MessageController類主要功能:
(1)參數校驗;(2)調用MessageService進行業務邏輯操作;
MessageService類主要功能:
(1)調用MessageMapper接口進行數據庫操作;
MessageMapper接口主要功能:
(1)執行SQL語句;
3.2?MessageController類
package com.example.springbootdemo2.controller;import com.example.springbootdemo2.model.MessageInfo;
import com.example.springbootdemo2.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.ArrayList;
import java.util.List;// 新增留言
@RequestMapping("/message")
@RestController
public class MessageController {@Autowiredprivate MessageService messageService;@RequestMapping("/publish")public Boolean publishMessage(MessageInfo messageInfo){// 參數校驗:Controllerif(!StringUtils.hasLength(messageInfo.getFrom())|| !StringUtils.hasLength(messageInfo.getTo())|| !StringUtils.hasLength(messageInfo.getMessage())){return false;}// 添加留言:ServicemessageService.addMessage(messageInfo);return true;}// 返回所有留言信息@RequestMapping("/getMessageList")public List<MessageInfo> getMessageList(){return messageService.getMessageInfo();}
}
3.3?MessageService類
package com.example.springbootdemo2.service;import com.example.springbootdemo2.mapper.MessageMapper;
import com.example.springbootdemo2.model.MessageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;@Service
public class MessageService {@Autowiredprivate MessageMapper messageMapper;public void addMessage(MessageInfo messageInfo){messageMapper.insertMessage(messageInfo);}public List<MessageInfo> getMessageInfo(){return messageMapper.selectAllMessage();}
}
3.4?MessageMapper接口
package com.example.springbootdemo2.mapper;import com.example.springbootdemo2.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 MessageMapper {@Insert("insert into message_info(`from`,`to`,`message`) values (#{from},#{to},#{message})")void insertMessage(MessageInfo messageInfo);@Select("select* from message_info where delete_flag=0")List<MessageInfo> selectAllMessage();
}
4. 前端代碼
<!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/getMessageList",type:"get",success:function(messages){// 參數為后端返回結果(變量名任意)for(var m of messages){// 拼接留言// 拼接節點的HTML,直接將HTML添加到container中var divE = "<div>" + m.from + "對" + m.to + "說:" + m.message + "</div>";// 把節點添加到頁面上$(".container").append(divE);}}})function submit() {//1. 獲取留言的內容var from = $('#from').val();var to = $('#to').val();var say = $('#say').val();if (from == '' || to == '' || say == '') {return;}// 提交留言$.ajax({url: "/message/publish",type: "post",data: {"from": from,"to": to,"message": say},success: function (result) {if (result) {// 留言添加成功//2. 拼接節點的HTML,直接將HTML添加到container中// document.createElement('div');var divE = "<div>" + from + "對" + to + "說:" + say + "</div>";//3. 把節點添加到頁面上$(".container").append(divE);//4. 清空輸入框的值$('#from').val("");$('#to').val("");$('#say').val("");} else {// 留言添加失敗alert("留言發布失敗")}}})}</script>
</body></html>
5. 單元測試
5.1?后端接口測試
(可以使用postman或Chrome)
可以在服務器日志中查看到相關信息:
需在數據庫中進行是否成功的驗證:
5.2 使用前端頁面測試
可以在服務器日志中查看到相關信息:
需在數據庫中進行是否成功的驗證:
一般報錯檢錯步驟:
(1)根據后端接口使用postman或Chrome構造請求,檢查后端代碼是否有錯;
若后端接口訪問無錯誤則說明錯誤出現在前端或前后端交互;
(2)若使用Chrome,則按F12看瀏覽器是否報錯,根據報錯信息定位錯誤代碼;
若無錯誤則需檢查請求是否發往后端,可以在后端服務器對應方法處打印日志(使用slf4j),若前端進行操作后,后端服務器處沒有執行改行日志的代碼,則說明前后端交互處出現錯誤;
(3)若后端、前后端交互、前端均沒有出現問題,可以進行清除前端與后端緩存;