零基礎做項目---五子棋對戰---day02

用戶模塊

完成注冊登錄,以及用戶分數管理~使用數據庫來保存上述用戶信息.

使用 MyBatis來連接并操作數據庫了

主要步驟:?

1.修改 Spring的配置文件,使數據庫可以被連接上.

2.創建實體類,用戶, User

3.創建Mapper接口~

4.實現MyBatis 的相關xml配置文件,來自動的實現數據庫操作

修改Spring的配置文件

將application.properties重命名為application.yml, 粘貼代碼

yml代碼:

spring:datasource:url: jdbc:mysql://127.0.0.1:3306/java_gobang?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8username: rootpassword: 密碼driver-class-name: com.mysql.cj.jdbc.Drivermybatis:mapper-locations: classpath:mapper/**Mapper.xmllogging:pattern:console: "[%-5level] - %msg%n"

創建數據庫

創建數據庫并且插入數據

create database if not exists java_gobang;use java_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, '張雨瀟', '123', 1000, 0, 0);
insert into user values (null, '李明', 'password1', 1200, 10, 6);
insert into user values (null, '王芳', 'password2', 1100, 8, 4);
insert into user values (null, '劉強', 'password3', 950, 12, 5);
insert into user values (null, '趙靜', 'password4', 980, 7, 3);
insert into user values (null, '孫鵬', 'password5', 1050, 11, 7);
insert into user values (null, '周麗', 'password6', 1020, 9, 4);
insert into user values (null, '鄭凱', 'password7', 1150, 15, 8);
insert into user values (null, '何敏', 'password8', 990, 10, 5);
insert into user values (null, '吳昊', 'password9', 1080, 13, 6);
insert into user values (null, '陳曉', 'password10', 930, 8, 3);
insert into user values (null, '楊洋', 'password11', 1120, 14, 9);
insert into user values (null, '林靜', 'password12', 1040, 11, 6);
insert into user values (null, '張偉', 'password13', 950, 7, 2);
insert into user values (null, '劉暢', 'password14', 1070, 12, 7);
insert into user values (null, '宋雨', 'password15', 990, 9, 4);
insert into user values (null, '唐鵬', 'password16', 1010, 10, 5);
insert into user values (null, '許娟', 'password17', 920, 6, 2);
insert into user values (null, '高飛', 'password18', 960, 8, 3);
insert into user values (null, '鐘麗', 'password19', 980, 7, 3);
insert into user values (null, '魏強', 'password20', 1100, 10, 5);

命令行運行即可

約定前后端交互接口

登錄接口

  • 請求
    POST /login HTTP/1.1
    Content-Type: application/x-www-form-urlencoded
    username=zhangsan&password=123
    

  • 響應
    HTTP/1.1 200 OK
    Content-Type: application/json
    {"userId": 1,"username": "zhangsan","score": 1000,"totalCount": 0,"winCount": 0
    }
    
    如果登錄失敗,返回一個無效的用戶對象,每個屬性為空或為默認值,例如 userId=0
    

    注冊接口

  • 請求
    POST /register HTTP/1.1
    Content-Type: application/x-www-form-urlencoded
    username=zhangsan&password=123
    

  • 響應
    HTTP/1.1 200 OK
    Content-Type: application/json
    {"userId": 1,"username": "zhangsan","score": 1000,"totalCount": 0,"winCount": 0
    }
    

    獲取用戶信息接口

  • 請求
    GET /userInfo HTTP/1.1
    
     
  • 響應
    HTTP/1.1 200 OK
    Content-Type: application/json
    {"userId": 1,"username": "zhangsan","score": 1000,"totalCount": 0,"winCount": 0
    }
    

編寫用戶實體

package com.example.java_gobang.model;public class User {private int userId;private String username;private String password;private int score;private int totalCount;private int winCount;public int getUserId() {return userId;}public void setUserId(int userId) {this.userId = userId;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public int getScore() {return score;}public void setScore(int score) {this.score = score;}public int getTotalCount() {return totalCount;}public void setTotalCount(int totalCount) {this.totalCount = totalCount;}public int getWinCount() {return winCount;}public void setWinCount(int winCount) {this.winCount = winCount;}
}

創建Mapper接口

UserMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.java_gobang.model.UserMapper"><insert id="insert">insert into user values (null, #{username}, #{password}, 1000, 0, 0);</insert><select id="selectByName" resultType="com.example.java_gobang.model.User">select * from user where username = #{username};</select></mapper>

UserMapper

package com.example.java_gobang.model;import org.apache.ibatis.annotations.Mapper;@Mapper
public interface UserMapper {//插入一個用戶, 用于注冊功能void insert(User user);//根據用戶名, 來查詢用戶的詳細信息, 用于登錄User selectByName(String username);
}

UserAPI

package com.example.java_gobang.api;import com.example.java_gobang.model.User;
import com.example.java_gobang.model.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;@RestController
public class UserAPI {@Autowiredprivate UserMapper userMapper;@PostMapping("/login")@ResponseBodypublic Object login(String username, String password, HttpServletRequest request) {//關鍵操作: 根據username去數據庫查詢// 如果能找到匹配的用戶并且密碼一致, 就確認為登陸成功User user = userMapper.selectByName(username);if (user == null || !user.getPassword().equals(password)) {return new User(); //這是空對象 說明登錄失敗}//這里的true表示如果會話存在, 那么返回session, 不存在創建一個新的會話返回HttpSession httpSession = request.getSession(true);httpSession.setAttribute("user", user);return user;}@PostMapping("/register")@ResponseBodypublic Object register(String username, String password) {try {User user = new User();user.setUsername(username);user.setPassword(password);//天梯分數新手默認1200user.setScore(1200);user.setWinCount(0);user.setTotalCount(0);userMapper.insert(user);return user;} catch (org.springframework.dao.DuplicateKeyException e) {//key重復異常User user = new User();return user;}}@PostMapping("/userInfo")@ResponseBodypublic Object getUserInfo(HttpServletRequest request) {try {HttpSession httpSession = request.getSession(false);User user = (User) httpSession.getAttribute("user");return user;} catch (NullPointerException e) {return new User();}}
}

其中有登錄, 注冊, 查詢用戶信息的方法

其中@PostMapping("/register"):映射HTTP POST請求到/register路徑。

會話機制講解

request.getSession(true)
  • 功能getSession(true)方法會檢查當前請求是否已經有一個會話。如果有,會返回這個會話。如果沒有,它會創建一個新的會話并返回。
  • 參數true:表示如果沒有現有的會話,創建一個新的會話。
HttpSession
  • 會話對象HttpSession是一個接口,提供了一種在多個請求中標識用戶的方法,并且能夠存儲用戶會話期間的信息。典型的用法包括存儲用戶的登錄狀態、購物車內容等。
httpSession.setAttribute("user", user)
  • 設置屬性setAttribute方法用于在會話中存儲一個鍵值對。這里的鍵是"user",值是用戶對象user
  • 作用:將當前登錄的用戶信息存儲到會話中,以便在后續的請求中可以方便地獲取到用戶信息。

登錄注冊的前端頁面

登錄的html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>登錄</title>
</head>
<body><div class="nav">五子棋對戰</div><div class="login-container"><!-- 登錄界面對話框 --><div class="login-dialog"><h3>登錄</h3><!-- 這個表示一行 輸入用戶名的一行 --><div class="row"><span>用戶名</span><input type="text" id="username"></div><!-- 這個表示一行 輸入密碼的一行 --><div class="row"><span>密碼</span><input type="password" id="password"></div><!-- 提交按鈕 --><button id="submit">提交</button></div></div>
</body>
</html>

common.css和login.css

/* 公共的樣式 */
* {margin: 0;padding: 0;box-sizing: border-box;
}/* 設置圖片能夠覆蓋全部窗口 */
html, body {height: 100%;background-image: url(../image/background.jpg);background-repeat: no-repeat;background-position: center;background-size: cover;
}.nav {height: 50px;background-color: rgb(50, 50, 50);color: aliceblue;line-height: 50px;padding-left: 20px;
}

login.css

.login-container {height: calc(100% - 50px);display: flex;justify-content: center;align-items: center;
}.login-dialog {width: 400px;height: 400px;background-color: rgba(255, 255, 255, 0.8);border-radius: 10px;
}/* 標題 */
.login-dialog h3 {text-align: center;padding: 50px 0;
}/* 針對一行設置樣式 */
.login-dialog .row {width: 100%;height: 50px;display: flex;align-items: center;justify-content: center;
}.login-dialog .row span {width: 100px;font-weight: 700;
}#username, #password {width: 200px;height: 40px;font-size: 20px;line-height: 40px;padding-left: 10px;border: none;outline: none;border-radius: 10px;
}.button-container {display: flex;justify-content: center;
}#submit {width: 300px;height: 50px;background-color: rgb(0, 128, 0);color: white;border: none;outline: none;border-radius: 10px;margin-top: 20px;
}#submit:active {background-color: #666;
}/* 公共的樣式 */
* {margin: 0;padding: 0;box-sizing: border-box;
}/* 設置圖片能夠覆蓋全部窗口 */
html, body {height: 100%;background-image: url(../image/background.jpg);background-repeat: no-repeat;background-position: center;background-size: cover;
}.nav {height: 50px;background-color: rgb(50, 50, 50);color: aliceblue;line-height: 50px;padding-left: 20px;
}

引入jQuery

百度搜索?jQuery cdn

比如使用字節的

https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/jquery/1.7.2/jquery.min.js

全選保存

引入:

<script src="./js/jquery.min.js"></script>

處理登錄的代碼

<script>let usernameInput = document.querySelector('#username');let passwordInput = document.querySelector('#password');let submitButton = document.querySelector('#submit');submitButton.onclick = function() {// 禁用提交按鈕,避免重復提交submitButton.disabled = true;$.ajax({type: 'post',url: '/login',data: {username: usernameInput.value,password: passwordInput.value,},success: function(body) {// 請求執行成功之后的回調函數// 判定當前是否登錄成功~// 如果登錄成功, 服務器會返回當前的 User 對象.// 如果登錄失敗, 服務器會返回一個空的 User 對象.if (body && body.userId > 0) {// 登錄成功alert("登錄成功!");// 重定向跳轉到 "游戲大廳頁面".location.assign('/game_hall.html');} else {alert("登錄失敗!, 請檢查密碼是否正確");}},error: function() {// 請求執行失敗之后的回調函數alert("登錄失敗!");},complete: function() {//AJAX請求完成后重新啟用按鈕submitButton.disabled = false;}});}</script>

驗證登錄頁面

啟動服務器

訪問?http://127.0.0.1:8080/login.html

注冊樣式

與登錄大差不差

<div class="nav">五子棋對戰</div><div class="login-container"><!-- 登錄界面的對話框 --><div class="login-dialog"><!-- 提示信息 --><h3>注冊</h3><div class="row"><span>用戶名</span><input type="text" id="username"></div><div class="row"><span>密碼</span><input type="password" id="password"></div><!-- 提交按鈕 --><div class="row"><button id="submit">提交</button></div></div></div> 

script代碼

<script src="js/jquery.min.js"></script><script>let usernameInput = document.querySelector('#username');let passwordInput = document.querySelector('#password');let submitButton = document.querySelector('#submit');submitButton.onclick = function() {// 禁用提交按鈕,避免重復提交submitButton.disabled = true;$.ajax({type: 'post',url: '/register',data: {username: usernameInput.value,password: passwordInput.value,},success: function(body) {// 如果注冊成功, 就會返回一個新注冊好的用戶對象. if (body && body.username) {// 注冊成功!alert("注冊成功!")location.assign('/login.html');} else {alert("注冊失敗!");}}, error: function() {alert("注冊失敗!");},complete: function() {//AJAX請求完成后重新啟用按鈕submitButton.disabled = false;}});}</script>

注冊功能驗證

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/44541.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/44541.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/44541.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

MySQL安全值守常用語句

一、用戶權限設置 1、Mysql中用戶是如何定義的 用戶名主機域 10.0.0.5110.0.0.%%10.0.0.0/255.255.255.0Db01Localhost127.0.0.1 2、用戶創建 create user xinjing% identified by 123 3、用戶刪除 drop user username&#xff1b;username 是要刪除的用戶名:如 drop user root…

GDidees CMS v3.9.1 本地文件泄露漏洞(CVE-2023-27179)

前言 CVE-2023-27179 是一個影響 GDidees CMS v3.9.1 及更低版本的任意文件下載漏洞。這個漏洞存在于 /_admin/imgdownload.php 文件中&#xff0c;攻擊者可以通過向 filename 參數傳遞惡意輸入來下載服務器上的任意文件。 漏洞的根源在于對用戶輸入的 filename 參數處理不當…

【C++修行之道】string類練習題

目錄 387. 字符串中的第一個唯一字符 125. 驗證回文串 917. 僅僅反轉字母 415. 字符串相加&#xff08;重點&#xff09; 541. 反轉字符串 II 387. 字符串中的第一個唯一字符 字符串中的第一個唯一字符 - 力扣&#xff08;LeetCode&#xff09; 給定一個字符串 s &#…

中霖教育怎么樣?稅務專業可以考哪些證書?

在稅務專業領域&#xff0c;專業技能的認證對職業發展至關重要。以下為稅務專業相關可以考的證書&#xff1a; 1. 注冊稅務師資格證書&#xff1a;該證書是稅務專業人士的關鍵資質&#xff0c;使持證者可以從事稅務相關工作。 2. 會計職稱證書&#xff1a;會計系列證書分為初…

Linux 安裝 docker-compose

安裝 docker安裝 安裝docker-compose github安裝 版本查詢 地址: github地址 選擇自己想要安裝的版本 修改以下語句版本號 curl -L https://github.com/docker/compose/releases/download/1.27.4/docker-compose-$(uname -s)-$(uname -m) -o /usr/local/bin/docker-compo…

筆記本系統

筆記本更新升級 筆記本購入太早&#xff0c;所用內存只有4G&#xff0c;通過更好內存條升級系統性能 查看電腦支持內存大小 cmd命令輸入wmic memphysical get maxcapacity 這串數字就是電腦最大支持內存數值&#xff0c;做除法除兩次1024&#xff01;&#xff0c;得出來的…

查看oracle ojdbc所支持的JDBC驅動版本

oracle jcbc驅動的下載地址參考&#xff1a;JDBC and UCP Downloads page 其實上文中對ojdbc所支持的JDBC驅動版本已經有說明了&#xff0c;不過&#xff0c;因為oracle的驅動包很多時間&#xff0c;都是在公司內部私服里上傳維護的&#xff0c;上傳的時候&#xff0c;可能又沒…

flutter 實現AppStore左右滑動

在AppStore中如何實現左右滑動&#xff0c;因為使用PageView會居中顯示&#xff0c;不會居左顯示&#xff0c;目前沒有找到解決方案&#xff0c;我使用的方案是ListView自定義physics實現的。 代碼 SizedBox(width: 200,height: 400,child: ListView.builder(scrollDirection:…

Java中實現二維數組(矩陣)的轉置

在矩陣運算中&#xff0c;矩陣的轉置是一個基本操作&#xff0c;即將矩陣的行變成列&#xff0c;列變成行。在Java中&#xff0c;我們可以通過編寫一個方法來實現二維數組的轉置。下面&#xff0c;我將詳細介紹如何在Java中完成這一任務&#xff0c;并提供完整的代碼示例。 編…

鴻蒙語言基礎類庫:【@ohos.util.TreeSet (非線性容器TreeSet)】

非線性容器TreeSet 說明&#xff1a; 本模塊首批接口從API version 8開始支持。后續版本的新增接口&#xff0c;采用上角標單獨標記接口的起始版本。開發前請熟悉鴻蒙開發指導文檔&#xff1a;gitee.com/li-shizhen-skin/harmony-os/blob/master/README.md點擊或者復制轉到。 T…

HDFS 塊重構和RedundancyMonitor詳解

文章目錄 1. 前言2 故障塊的重構(Reconstruct)2.1 故障塊的狀態定義和各個狀態的統計信息2.2 故障文件塊的查找收集2.5.2.1 misReplica的檢測2.5.2.2 延遲隊列(postponedMisreplicatedBlocks)的構造和實現postponedMisreplicatedBlocks中Block的添加postponedMisreplicatedBloc…

綠盟培訓入侵排查

一、webshell 排查 1、文件特征 2、windows 3、linux 4、內存馬 二、web 日志排查 1、日志排查 2、中間件報錯排查 三、服務器失陷處置

Element-UI Select組件使用value-key屬性,讓綁定值可以為一個對象

當我們使用 Elemet UI 的 Select 組件的綁定值是一個對象 :value="item" 如: <el-form-item label="選擇應用" prop="appInfo"><el-select v-model=

每日一題cf

文章目錄 Swap and Reverse題意&#xff1a;題解&#xff1a;代碼&#xff1a; Swap and Reverse 題意&#xff1a; 給定一個長度為n的正整數數組&#xff0c;給定k。可以進行任意次一下操作 選定 i i i&#xff0c;交換 a i a_{i} ai?和 a i 2 a_{i2} ai2?的值選定 i i …

Windows環境人大金倉數據庫命令常規操作

Windows環境人大金倉數據庫命令常規操作 下文將介紹人大金倉數據庫常見命令操作&#xff0c;包括具體使用命令如創建數據庫、創建用戶、授權等相關操作。 1、打開命令提示符窗口 找到數據庫安裝目錄進入server/bin目錄&#xff0c;輸入cmd,打開命令提示符窗口&#xff0c;如…

Java getSuperclass和getGenericSuperclass

1.官方API對這兩個方法的介紹 getSuperclass : 返回表示此 Class 所表示的實體&#xff08;類、接口、基本類型或 void&#xff09;的超類的 Class。如果此 Class 表示 Object 類、一個接口、一個基本類型或 void&#xff0c;則返回 null。如果此對象表示一個數組類&#xff…

探秘微信廣告設計組:一位產品體驗設計師的日常與成長

目錄 我的工位&#xff1a;靈感與回憶的匯聚地 我們的設計&#xff1a;用心定格每一個瞬間 設計的多樣性&#xff1a;從社交廣告到過年IP形象 咖啡與工作的日常&#xff1a;從抵觸到入坑 廣告設計&#xff1a;我選擇&#xff0c;我熱愛 實習生的培養&#xff1a;實踐與思…

Qt(四)事件

文章目錄 一、概念二、&#xff08;一&#xff09;&#xff08;二&#xff09;QImage類&#xff08;三&#xff09;鼠標事件和鍵盤事件1. 鼠標事件2. 鍵盤事件 &#xff08;四&#xff09;定時器事件1. 采用定時器事件2. QTimer定時器類 三、 一、概念 事件是由窗口系統或者自…

充電樁項目

1. 多對一&#xff08;多個監測設備檢測&#xff0c;數據發送給一個服務器&#xff09; 2. 原理 充電樁溫度變化引起PT100阻值變換&#xff08;測溫電流衰減微弱&#xff0c;幾乎恒定&#xff0c;電壓隨之變化)&#xff0c;經過測溫模塊轉化成電壓的變化&#xff08;內部是電流…

小程序內容管理系統設計

設計一個小程序內容管理系統&#xff08;CMS&#xff09;時&#xff0c;需要考慮以下幾個關鍵方面來確保其功能完善、用戶友好且高效&#xff1a; 1. 需求分析 目標用戶&#xff1a;明確你的目標用戶群體&#xff0c;比如企業、媒體、個人博主等&#xff0c;這將決定系統的功…