外貿網站建設步驟網站設計公司多少錢
前一篇文章:網頁版五子棋—— WebSocket 協議-CSDN博客
目錄
·前言
一、編寫數據庫代碼
1.數據庫設計
2.配置 MyBatis
3.創(chuàng)建實體類
4.創(chuàng)建 UserMapper
二、前后端交互接口
1.登錄接口
2.注冊接口
3.獲取用戶信息
三、服務器開發(fā)
1.代碼編寫
2.測試后端接口
·結尾
·前言
? ? ? ? 本篇文章就開始五子棋項目的正式編寫了,在本篇文章中主要是對用戶模塊中服務器端的代碼進行編寫與介紹,用戶模塊主要負責用戶的注冊、登錄、分數記錄的功能,這里我們使用 MySQL 數據庫來存儲數據,服務器端是基于 Spring + MyBatis 來實現對數據庫的增、刪、查、改,本篇文章新增的代碼結構及內容如下圖所示:
????????下面就開始本篇文章的內容介紹。??
一、編寫數據庫代碼
1.數據庫設計
? ? ? ? 創(chuàng)建 user 表來保存用戶信息和分數信息,我們五子棋項目的數據庫設計非常簡單,具體的建庫建表及測試數據的代碼如下,復制粘貼到 MySQL 命令行中就可以完成創(chuàng)建:
create database if not exists spring_gobang charset utf8;use spring_gobang;drop table if exists user;
create table user (userId int primary key auto_increment,username varchar(50) unique,password varchar(50),score int, -- 天梯積分totalCount int, -- 比賽總場數winCount int -- 獲勝場數
);insert into user values (null, 'zhangsan', '123', 1000, 0, 0);
insert into user values (null, 'lisi', '123', 1000, 0, 0);
insert into user values (null, 'wangwu', '123', 1000, 0, 0);
insert into user values (null, 'zhaoliu', '123', 1000, 0, 0);
2.配置 MyBatis
? ? ? ? 在五子棋項目中我們使用 MyBatis 來連接并操作我們的數據庫,首先我們需要修改 Spring 的配置文件,使數據庫可以連接上,編輯 application.yml 的代碼如下,這里要注意根據自己數據庫的實際情況來對下面的部分配置加以修改:
spring:datasource:url: jdbc:mysql://127.0.0.1:3306/spring_gobang?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8username: rootpassword: 111111driver-class-name: com.mysql.cj.jdbc.Driver
? ? ? ? 如果都是按照我的代碼進行編寫,這里的配置需要記得修改數據庫的密碼。?
3.創(chuàng)建實體類
? ? ? ? 在代碼中創(chuàng)建實體類,用戶 User 類,它用來表示我們用戶的相關信息,具體代碼如下:
import lombok.Data;
// @Data 注解是為我們自動添加 get 與 set 方法的
@Data
public class User {private int userId;private String username;private String password;private int score;private int totalCount;private int winCount;
}
? ? ? ? 這里需要注意,User 類中的每個屬性名稱要與 user 表中對應的每個字段的名稱相同,不然·無法對應上。?
4.創(chuàng)建 UserMapper
? ? ? ? UserMapper 是一個接口,這里定義了用戶相關數據庫的操作,使用 MyBatis 中注解的方式來自動實現數據庫的操作,具體代碼及介紹如下所示:
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;@Mapper
public interface UserMapper {// 往數據庫中插入一個用戶,用于注冊功能@Insert("insert into user values (null, #{username}, #{password}, 1000, 0, 0)")void insert(User user);// 根據用戶名,來查詢用戶的詳細信息,用于登錄功能@Select("select * from user where username = #{username}")User selectByName(String username);
}
二、前后端交互接口
? ? ? ? 在我們用戶模塊,涉及前后端交互的接口主要有三個部分:
- 登錄接口
- 注冊接口
- 獲取用戶信息接口
? ? ? ? 這個前后端交互的接口,在約定的時候是有很多種交互方式的,我們下面約定好之后,后續(xù)的后端/前端代碼就都要嚴格的遵循這個約定來編寫代碼。?
1.登錄接口
? ? ? ? 登錄接口的設計如下:
- 請求:
????????????????POST /login HTTP/1.1
????????????????Content-Type:application/x-www-from-urlencoded
????????????????username=zhangsan&password=123
- 響應:
????????????????Http/1.1 200 OK
????????????????Content-Type:application/json
????????????????{
? ? ? ? ????????????????userId:1,
? ? ? ? ????????????????username:'zhangsan',
? ? ? ????????????????? score:1000,
? ? ? ????????????????? totalCount:0,
? ? ? ????????????????? winCount:0
????????????????}
- 登錄失敗:
????????????????返回一個無效的 user 對象,這個對象的所有屬性都為空,后續(xù)利用這里的 userId 是否為 0 來判斷登錄是否成功。
? ? ? ? 注意,以上接口格式要嚴格遵守,里面的數據只是以 zhangsan 為示例進行介紹,?
2.注冊接口
? ? ? ? 注冊接口設計如下:
- 請求:
????????????????POST /register?HTTP/1.1
????????????????Content-Type:application/x-www-from-urlencoded
????????????????username=zhangsan&password=123
- 響應:
????????????????Http/1.1 200 OK
????????????????Content-Type:application/json
????????????????{
? ? ? ? ????????????????userId:1,
? ? ? ? ????????????????username:'zhangsan',
? ? ? ????????????????? score:1000,
? ? ? ????????????????? totalCount:0,
? ? ? ????????????????? winCount:0
????????????????}
- 注冊失敗(比如用戶名重復):
????????????????返回一個無效的 user 對象,這個對象的所有屬性都為空,后續(xù)利用這里的 userId 是否為 0 來判斷注冊是否成功。
3.獲取用戶信息
? ? ? ? 從服務器獲取到當前登錄用戶的信息,程序運行過程中,用戶登錄之后,讓客戶端隨時通過這個接口,來訪問服務器獲取到用戶自身的信息,獲取用戶信息的接口設計如下:
- 請求:
????????????????Get /userInfo HTTP/1.1
- 響應:
????????????????HTTP/1.1 200 OK
????????????????Content-Type:application/json
????????????????{
? ? ? ? ????????????????userId:1,
? ? ? ? ????????????????username:'zhangsan',
? ? ? ????????????????? score:1000,
? ? ? ????????????????? totalCount:0,
? ? ? ????????????????? winCount:0
????????????????}
三、服務器開發(fā)
1.代碼編寫
? ? ? ? 在 api 包下創(chuàng)建 UserAPI 類,這里主要實現用戶相關操作的三個方法:
- login:用來實現登錄邏輯;
- register:用來實現注冊邏輯;
- getUserInfo:用來實現登錄成功后顯示用戶分數的信息。
? ? ? ? 具體代碼及詳細介紹如下所示:
import com.example.springgobang.model.User;
import com.example.springgobang.model.UserMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;@RestController
public class UserAPI {// 注入 userMapper 對象@Autowiredprivate UserMapper userMapper;// @PostMapping :路由映射@PostMapping("/login")// @ResponseBody :返回響應@ResponseBody// login 方法是處理登錄的邏輯public Object login(String username, String password, HttpServletRequest request) {// 關鍵操作,根據 username 去數據庫進行查詢.User user = userMapper.selectByName(username);// 如果能找到匹配的用戶,并且密碼也一致,就認為登錄成功if (user == null || !user.getPassword().equals(password)) {// 登錄失敗System.out.println("登錄失敗!");return new User();}System.out.println("[login] user = " + username);// getSession() 方法中參數為 true 表示當會話存在直接返回,不存在就創(chuàng)建會話// 用戶首次登錄,允許創(chuàng)建會話HttpSession httpSession = request.getSession(true);// 把 user 保存到 session 中,以便下次訪問服務器時,服務器可以正確識別出當前客戶端對應的正確身份信息httpSession.setAttribute("user",user);return user;}@PostMapping("/register")@ResponseBody// register 方法是處理注冊相關的邏輯public Object register(String username, String password) {// 為了預防注冊失敗(比如出現用戶名重復的情況)// 這里用 try--catch 包住try {User user = new User();user.setUsername(username);user.setPassword(password);userMapper.insert(user);return userMapper.selectByName(username);} catch (org.springframework.dao.DuplicateKeyException e) {// 注冊失敗,返回一個空的 User 對象return new User();}}@GetMapping("/userInfo")@ResponseBody// getUserInfo 方法用來處理獲取用戶信息的操作public Object getUserInfo(HttpServletRequest request) {// 避免獲取的用戶信息不存在,用 try--catch 包住try {// getSession() 方法中參數為 false 表示當會話存在直接返回,不存在也不創(chuàng)建新會話// 由于這是用戶登錄后的操作,所以登錄了就有會話,沒登錄就沒有會話// 這也可以讓我們感知到用戶是否進行了登錄HttpSession httpSession = request.getSession(false);// 從 session 中獲取登錄用戶的信息User user = (User) httpSession.getAttribute("user");return user;} catch (NullPointerException e) {// 當前用戶未登錄, 直接返回一個空的 User 對象return new User();}}
}
2.測試后端接口
? ? ? ? 編寫完代碼之后,我們來驗證一下代碼是否正確,功能是否正常,這里我們使用的測試工具是一個軟件 Postman ,首先我們要啟動我們的程序,然后使用 Postman 來測試我們后端的代碼,具體的測試過程及結果如下圖所示:
? ? ? ? 如上圖所示,服務器端關于用戶模塊的代碼及功能就都正確編寫完成了。?
·結尾
? ? ? ? 文章到此就要結束了,本篇文章主要介紹了五子棋項目中用戶模塊的服務器端代碼編寫、數據庫設計,以及規(guī)定了前后端交互的接口,文章中使用到的 Postman 是非常好用的接口測試工具,在后面的模塊中都會使用 Postman 來進行后端接口的測試,如果對本篇文章的內容有所疑惑,歡迎在評論區(qū)進行留言,如果感覺本篇文章還不錯也希望能收到你的三連支持,那么我們下一篇文章再見吧~~~