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