項目9-網頁聊天室1(注冊+Bycrpt加密)

1.準備工作

1.1.前端頁面展示?

1.2 數據庫的建立?

我們通過注冊頁面,考慮如何設計用戶表數據庫。

  1. 用戶id,userId
  2. 用戶名,唯一,username
  3. 用戶密碼,password(包括密碼和確認密碼ensurePssword【數據庫沒有該字段】)
  4. 同時還需要考慮是否需要將圖片和用戶進行分離

????????????????//我考慮的是將其合并在一起

????????????????//這樣做的好處是直接和userId相對應

????????????????//省去了其余的操作

? ? ? 5.需要存儲圖片名字(picname)

? ? ? 6.需要存儲圖片地址(path)

-- 數據庫
drop database if exists `chatroom`;
create database if not exists `chatroom` character set utf8;
-- 使用數據庫
use `chatroom`;DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`userId` INT PRIMARY KEY AUTO_INCREMENT,
`username` varchar(200) NOT NULL,
`password` varchar(200) NOT NULL,
`picname` varchar(200) NOT NULL,
`path` varchar(255) NOT NULL
);

2.前端代碼?

2.1 model

@Data
public class User {private Integer userId;private String username;private String password;private String picname;private String path;
}

2.2 service

package com.example.demo.service;import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;@org.springframework.stereotype.Service
public class UserService {@Autowiredprivate UserMapper userMapper;public Boolean insertUserInfo(String username,String password,String picname,String path){Integer influncefactor=userMapper.insertUserInfo(username,password,picname,path);if(influncefactor>0){return true;}return false;}}

2.3 controller

package com.example.demo.controller;import com.example.demo.config.AppConfig;
import com.example.demo.config.Result;
import com.example.demo.constant.Constant;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;import java.io.File;
import java.io.IOException;@RestController
@RequestMapping("/user")
public class UserController {@Autowiredprivate UserService userService;@Autowiredprivate BCryptPasswordEncoder bCryptPasswordEncoder;@RequestMapping("/register")public Result registerUser(@RequestParam MultipartFile file,String username,String password,String ensurePassword){//當舊密碼與新密碼所輸入的一樣,且都不為空才會進行后續操作if(!StringUtils.hasLength(username)||!StringUtils.hasLength(password)||!StringUtils.hasLength(ensurePassword)){return Result.fail(Constant.RESULT_CODE_MESSAGENULL,"你所輸入的信息為空,違規");}//兩個密碼必須一致才可以進行后續操作if(!password.equals(ensurePassword)){return Result.fail(Constant.RESULT_CODE_NOTSAMEPASSWORD,"兩次密碼輸入不一致,違規");}String fileName=file.getOriginalFilename();String path = Constant.SAVE_PATH +fileName;File dest=new File(path);//圖片可以是同一張圖片//直接上傳圖片try {file.transferTo(dest);} catch (IOException e) {e.printStackTrace();return Result.fail(Constant.RESULT_CODE_UPLOADPICFAIL,"圖片上傳失敗");}//同時要將密碼進行加密BCryptString newpassword=bCryptPasswordEncoder.encode(password);//將所輸入的數據存入數據庫中if(userService.insertUserInfo(username,newpassword,fileName,path)){return Result.success(true);}return Result.fail(Constant.RESULT_CODE_FAIL,"上傳數據庫失敗");}
}

3.前端接口測試

每個if語句都需要判斷一次

3.1 成功情況

3.2 用戶名相同情況

?3.3 有一個輸入為空的情況

3.4 兩次輸入的密碼不同?

4.考慮的問題,圖像為空

我們允許圖像為空,故需要考慮將本地的文件轉為MultipartFile。

數據庫存入默認頭像

根據文件路徑獲取 MultipartFile 文件_multipartfile他通過路徑獲取-CSDN博客

4.1 Controller更改

?

package com.example.demo.controller;import com.example.demo.config.Method;
import com.example.demo.config.Result;
import com.example.demo.constant.Constant;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;import java.io.File;
import java.io.IOException;@RestController
@RequestMapping("/user")
public class UserController {@Autowiredprivate UserService userService;@Autowiredprivate BCryptPasswordEncoder bCryptPasswordEncoder;@RequestMapping("/register")public Result registerUser(@RequestParam(required = false) MultipartFile file, String username, String password, String ensurePassword) {//當舊密碼與新密碼所輸入的一樣,且都不為空才會進行后續操作if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password) || !StringUtils.hasLength(ensurePassword)) {return Result.fail(Constant.RESULT_CODE_MESSAGENULL, "你所輸入的信息為空,違規");}//兩個密碼必須一致才可以進行后續操作if (!password.equals(ensurePassword)) {return Result.fail(Constant.RESULT_CODE_NOTSAMEPASSWORD, "兩次密碼輸入不一致,違規");}//需要查詢是否存在相同的username,若否則不能注冊,讓用戶重命名if (!userService.selectByUsername(username)) {return Result.fail(Constant.RESULT_CODE_SAMEUSERNAME, "用戶名不能相同,違規");}String fileName;MultipartFile mfile;String path;//如果圖片為空,則保存默認的圖片if (file == null) {fileName = Constant.PIC;path = Constant.SAVE_PATH +fileName;mfile = Method.getMulFileByPath(path);} else {fileName = file.getOriginalFilename();path = Constant.SAVE_PATH +fileName;mfile=file;}File dest=new File(path);try {mfile.transferTo(dest);} catch (IOException e) {e.printStackTrace();return Result.fail(Constant.RESULT_CODE_UPLOADPICFAIL,"圖片上傳失敗");}//同時要將密碼進行加密BCryptString newpassword=bCryptPasswordEncoder.encode(password);//將所輸入的數據存入數據庫中if(userService.insertUserInfo(username,newpassword,fileName,path)){return Result.success(true);}return Result.fail(Constant.RESULT_CODE_FAIL,"上傳數據庫失敗");}
}

4.2 Method類

?

package com.example.demo.config;import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;public class Method {public static MultipartFile getMulFileByPath(String picPath) {FileItem fileItem = createFileItem(picPath);MultipartFile mfile = new CommonsMultipartFile(fileItem);return mfile;}public static FileItem createFileItem(String filePath) {FileItemFactory factory = new DiskFileItemFactory(16, null);String textFieldName = "textField";int num = filePath.lastIndexOf(".");String extFile = filePath.substring(num);FileItem item = factory.createItem(textFieldName, "text/plain", true,"MyFileName" + extFile);File newfile = new File(filePath);int bytesRead = 0;byte[] buffer = new byte[8192];try{FileInputStream fis = new FileInputStream(newfile);OutputStream os = item.getOutputStream();while ((bytesRead = fis.read(buffer, 0, 8192))!= -1){os.write(buffer, 0, bytesRead);}os.close();fis.close();}catch (IOException e){e.printStackTrace();}return item;}}

4.3 前端測試?

5.前后端交互

5.1 register.html

</head>
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>用戶注冊界面</title><link rel="stylesheet" href="css/common.css"><link rel="stylesheet" href="css/register.css"><link rel="stylesheet" href="css/upload.css">
</head>
<body><!-- 導航欄 --><div class="nav">網頁聊天</div><div class="container"><h1>新用戶注冊</h1><br><form enctype="multipart/form-data" id="file_upload" class="headForm" onsubmit="return false" action="##"> <div id="test-image-preview" class="iconfont icon-bianjitouxiang"><input type="file" name="test" id="test-image-file" class="fileHead" accept="image/gif, image/jpeg, image/png, image/jpg" multiple="multiple"></div><div class="headMain"><span class="file">上傳頭像</span><p id="test-file-info" class="fileName"></p></div><br>       <div><span class="p">*</span><label for="username">用戶名</label><input type="text" name="" id="username" placeholder="" class="register"><br><br><span class="q">*</span><label for="pwd">登錄密碼</label><input type="password" name="" id="pwd" class="register"><br><br><span class="q">*</span><label for="c_pwd">確認密碼</label><input type="password" name="" id="c_pwd" class="register"><br><br><input type="checkbox" class="checkbox" name=""><span style="font-size:15px">我已閱讀并同意《用戶注冊協議》</span><br><br><input type="submit" name="" value="同意以上協議并注冊" class="submit" onclick="register(this)"><br><a href="login.html" class="left">返回首頁</a><a href="login.html" class="right">開始登錄</a></form></div></div>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript" src="js/register.js"></script>
<script type="text/javascript" src="js/upload.js"></script>
<script></script>
</body>
</html>

5.2 register.js

var checkbox=document.getElementsByClassName('checkbox');
function register(btn){if(checkbox[0].checked==true){submitmessage();}else{alert("請先閱讀并同意《用戶注冊協議》!")}
}function submitmessage(){var formData = new FormData();formData.append('file', $('.fileHead')[0].files[0]);formData.append('username', $("#username").val());formData.append('password', $("#pwd").val());formData.append('ensurePassword', $("#c_pwd").val());var name11 = formData.get("#username");$.ajax({type: 'post',url: '/user/register',processData: false,async: false,contentType: false,cache: false,// 使用同步操作timeout: 50000, //超時時間:50秒data: formData,success: function (result) {    // 返回成功// console.log(result);console.log(name11);if(result!=null&&result.status==200){alert("注冊賬號成功,跳轉到登陸頁面,開始進行聊天吧!")location.href="login.html"return;}else if(result!=null&&result.status==-10){alert("用戶名不能相同,違規");}else if(result!=null&&result.status==-8){alert("兩次密碼輸入不一致,違規");}else if(result!=null&&result.status==-6){alert("你所輸入的信息為空,違規");}else{alert("注冊錯誤,請聯系工作人員")}},error: function () {alert("接口錯誤");       // 返回失敗}})
}

5.3 upload.js

var fileInput = document.getElementById('test-image-file'),//文件框,里面存的是文件,fileHeadinfo = document.getElementById('test-file-info'),//文件名preview = document.getElementById('test-image-preview');//文件框,頭像顯示界面dataBase64 = '',preview.style.backgroundImage = 'url(../img/個人頭像.png)';    //默認顯示的圖片// 監聽change事件:fileInput.addEventListener('change', upImg);// 頭像上傳邏輯函數
function upImg() {preview.style.backgroundImage = '';       // 清除背景圖片if (!fileInput.value) {     // 檢查文件是否選擇:(此時文件中什么都沒選擇)$('#test-image-preview').addClass('icon-bianjitouxiang');info.innerHTML = '沒有選擇文件';} else {$('#test-image-preview').removeClass('icon-bianjitouxiang');info.innerHTML = '';//此時上傳文件成功}var file = fileInput.files[0];    // 獲取File引用var size = file.size;if (size >= 100 * 1024 * 1024) {     //判斷文件大小info.innerHTML = '文件大于100兆不行!';preview.style.backgroundImage = '';$('#test-image-preview').addClass('icon-bianjitouxiang');return false;}if (file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {    // 獲取File信息:info.innerHTML = '不是有效的圖片文件!';preview.style.backgroundImage = '';$('#test-image-preview').addClass('icon-bianjitouxiang');return;}// 讀取文件:var reader = new FileReader();reader.onload = function (e) {dataBase64 = e.target.result;     // 'data:image/jpeg;base64,/9j/4AAQSk...(base64編碼)...}'        preview.style.backgroundImage = 'url(' + dataBase64 + ') ';preview.style.backgroundRepeat = 'no-repeat';preview.style.backgroundSize = ' 100% 100%';};// 以DataURL的形式讀取文件:reader.readAsDataURL(file);// console.log(file);
}

5.4 upload.css

.reHead{margin: 15px 4%; 
}
.headForm{text-align: center;padding: 40px 0 70px 0;
}
#test-image-preview {position: relative;display: inline-block;width: 100px;height: 100px;border-radius: 50px;background: #F5F5F5;color: #fff;font-size: 60px;text-align: center;line-height: 100px;background-size: contain;background-repeat: no-repeat;background-position: center center;margin-bottom: 26px;
}
.fileHead{position: absolute;width: 100px;height: 100px;right: 0;top: 0;opacity: 0;
}
.content-format {font-size: 12px;font-weight: 400;color: rgba(153, 153, 153, 1);
}
.headMain{height: 40px;
}
.file {position: relative;background: #fff;color: #F39800;font-weight:800;
}
.file input {position: absolute;font-size: 12px;right: 0;top: 0;opacity: 0;
}
.fileName {line-height: 28px;font-size: 12px;font-weight: 400;color: rgba(51, 51, 51, 1);
}
.but{text-align: center;
}
.orangeHead{width: 40%;height: 40px;background: #f60;border: none;
}
.orangeHead a{color: #fff;
}

5.5 register.css

body{background: url("../img/coolgirl.jpg");background-size:100% 100%;background-attachment: fixed;
}.container{position: absolute;top: 50%;left: 50%;transform: translate(-50%,-50%);}img{width: 4rem;height: 4rem;margin-left: 50%;transform: translateX(-50%);margin-top: 0.853rem;border-radius: 50%;}#js_logo_img{width: 4rem;height: 4rem;position: absolute;left: 50%;transform: translateX(-50%);top: 30%;opacity: 0;}h2{color: #000066;font-size: 0.853rem;text-align: center;margin: 0;}form{width: 450px;margin: 0 auto;background: #FFF;border-radius: 15px;position: relative;}h1{font-size: 28px;text-align: center;color: #FFF;}.p{color: red;margin-left: 33px;display: inline-block;/* 不占單獨一行的塊級元素 */}label{font-size: 18px;font-weight: bold;}.register{height: 35px;width: 300px;}.q{color:red;margin-left:17px;display:inline-block;}.checkbox{margin-left: 100px;display: inline-block;width: 15px;height: 15px;}.submit{border-radius: 7px;margin-left: 150px;height: 35px;width: 150px;background-color: #000;border: none;display: block;padding: 0;color: #FFF;font-weight: bold;cursor: pointer;}a{text-decoration: none;font-weight: bold;}.left,.right{position: absolute;bottom: 20px;}.left{left: 20px;}.right{right: 20px;}

5.6 common.css

/* 放置頁面的公共樣式 *//* 去除瀏覽器默認樣式 */
* {margin: 0;padding: 0;box-sizing: border-box;
}/* 設定頁面高度 */
html, body {height: 100%;
}/* 設定導航欄的樣式 */
.nav {height: 50px;background-color: black;color: rgb(255, 255, 255);/* 使用彈性布局, 讓導航欄內部的元素, 垂直方向居中 */display: flex;align-items: center;/* 讓里面的元素距離左側邊框, 有點間隙 */padding-left: 20px;
}

5.7 測試

注冊成功!!!

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

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

相關文章

【簡單介紹下Milvus】

&#x1f308;個人主頁: 程序員不想敲代碼啊 &#x1f3c6;CSDN優質創作者&#xff0c;CSDN實力新星&#xff0c;CSDN博客專家 &#x1f44d;點贊?評論?收藏 &#x1f91d;希望本文對您有所裨益&#xff0c;如有不足之處&#xff0c;歡迎在評論區提出指正&#xff0c;讓我們共…

網絡3--網絡通信的深度理解(端口號)

網絡通信的進一步理解 兩個主機間進行通信&#xff0c;其實是兩個主機間的軟件進行通信&#xff0c;軟件也就是可執行程序&#xff0c;運行時就是進程&#xff0c;所以也為進程間通信。 進程間通信需要共享資源&#xff0c;這里兩個主機間的共享資源是網絡&#xff0c;利用的是…

Visual Studio生成C++的DLL文件(最簡單版)

前言 當你在使用C編寫一些可重用的代碼時&#xff0c;將其打包成一個動態鏈接庫&#xff08;DLL&#xff09;可以使其更容易地被其他項目或者程序調用和使用。Visual Studio提供了一種簡單的方式來生成C的DLL文件。下面是一個關于如何在Visual Studio中生成C的DLL文件的簡單教…

【 第一性原理計算方法及應用】

第一性原理計算方法及應用述

對接極速行情丨DolphinDB MDL 行情插件使用指南

通聯數據依托于金融大數據&#xff0c;結合人工智能技術為投資者提供個性化、智能化、專業化投資服務&#xff0c; MDL 則是通聯數據提供的高頻行情數據服務。DolphinDB 提供了能夠從 MDL 服務器獲取高頻行情數據的 DolphinDB MDL 插件&#xff0c;幫助用戶方便地通過 DolphinD…

算法day06

第一題 1658. 將 x 減到 0 的最小操作數 如題上述&#xff1a; 本題原來的意思給定一個數字x&#xff0c;從數組的左邊或者右邊 使用x減去數組中的數字&#xff0c;直到減去最后一個數字為0時&#xff0c;返回最小的操作次數&#xff1b;如果最終減去的數組中的數字之后不能得…

HR系統組合漏洞挖掘過程

前言 某天在項目中遇到了一個奇怪的人才管理系統&#xff0c;通過FOFA&#xff08;會員可在社區獲取&#xff09;進行了一番搜索&#xff0c;發現了該系統在互聯網上的使用情況相當廣泛。于是&#xff0c;我開始了后續的審計過程。 在搜索過程中&#xff0c;我偶然間找到了一份…

「TypeScript系列」TypeScript 基礎類型

文章目錄 一、TypeScript 基礎類型1. **Number**: 用于表示數字。可以是整數或浮點數。2. **String**: 用于表示文本類型的數據。3. **Boolean**: 表示邏輯值&#xff1a;true 或 false。4. **Array**: 表示一組值。TypeScript 使用泛型&#xff08;generics&#xff09;來定義…

Mysql存儲引擎對比

存儲引擎InnoDBMyISAM文件存儲結構.frm文件&#xff1a;存放表結構的定義信息 .ibd文件或.ibdata文件&#xff1a;存放InnoDB數據&#xff08;數據和索引&#xff09;【獨享表空間】每個表一個.ibd文件【共享表空間】所有表使用一個.ibdata文件- .frm文件&#xff1a;存放表結構…

Nginx靜態壓縮和代碼壓縮,提高訪問速度!

一、概述 基于目前大部分的應用&#xff0c;都使用了前后端分離的框架&#xff0c;vue的前端應用&#xff0c;也是十分的流行。不知道大家有沒有遇到這樣的問題&#xff1a; 隨著前端框架的頁面&#xff0c;功能開發不斷的迭代&#xff1b;安裝的依賴&#xff0c;不斷的增多&a…

機器學習【簡述】

什么是機器學習 機器學習研究的是計算機怎么模擬人類的學習行為&#xff0c;以獲取的知識或技能&#xff0c;并重新組織已有的知識結構使之不斷改善自身。簡單一點說&#xff0c;就是計算機從數據中學習初規律和模式&#xff0c;以應用在新數據上做預測的任務。近年來互聯網數…

無人機的用途

無人機&#xff0c;即無人駕駛飛機&#xff0c;其用途廣泛且多樣&#xff0c;涉及到多個領域。 在農業領域&#xff0c;無人機通過搭載各種傳感器和相機&#xff0c;可以對農田進行空中巡視&#xff0c;收集農田數據&#xff0c;如土壤含水量、氣溫、濕度等&#xff0c;以及植…

詳細的性能分析和調優的示例過程:

當面臨數據庫查詢性能下降的問題時&#xff0c;以下是一個詳細的性能分析和調優的示例過程&#xff1a; ### 1. 監控和識別問題 假設你負責維護一個電子商務網站數據庫&#xff0c;最近用戶反映搜索功能響應慢。你立即使用數據庫監控工具&#xff08;如Prometheus、Grafana&am…

Ardupilot開源飛控工程項目編譯回顧

Ardupilot開源飛控工程項目編譯回顧 1. 源由2. 工程編譯3. 命令列表3.1 工作環境設置3.2 獲取工程代碼3.3 建立編譯環境3.4 編譯工程代碼3.5 保存編譯結果3.6 清理編譯結果3.7 編譯設備目標 4. 補充 1. 源由 最近&#xff0c;有點莫名的連續遇到了2次Ardupilot編譯報錯。百思不…

Quartz.Net(2)——NetCore3.1整合Quartz.Net

在上篇文章中Quartz.Net(1) 已經介紹了Quartz.Net的基本運用&#xff0c;該篇文章中將主要介紹NetCore3.1如何整合Quartz.Net&#xff0c;在后臺運行定時job&#xff0c;并運用到上篇文章講到的介紹點。 1 導入Nuget包 <PackageReference Include"Quartz" Versio…

PyTorch中的torch.cuda.amp.autocast

torch.cuda.amp.autocast的使用 torch.cuda.amp.autocast是PyTorch中一種自動混合精度計算的方法&#xff0c;它允許在深度學習模型的訓練過程中自動執行混合精度計算&#xff0c;從而加快訓練速度并減少顯存占用。 在使用torch.cuda.amp.autocast時&#xff0c;一般會將模型…

Ubuntu系統如何使用寶塔面板搭建HYBBS論壇并發布公網遠程訪問

文章目錄 前言1. HYBBS網站搭建1.1 HYBBS網站安裝1.2 HYBBS網站測試1.3. cpolar的安裝和注冊 2. 本地網頁發布2.1.Cpolar臨時數據隧道2.2.Cpolar穩定隧道&#xff08;云端設置&#xff09;2.3.Cpolar穩定隧道&#xff08;本地設置&#xff09; 3.公網訪問測試總結 前言 在國內…

【智能算法】河馬優化算法(HO)原理及實現

目錄 1.背景2.算法原理2.1算法思想2.2算法過程 3.結果展示4.參考文獻5.代碼獲取 1.背景 2024年&#xff0c;MH Amiri受到自然界河馬社會行為啟發&#xff0c;提出了河馬優化算法&#xff08;Hippopotamus Optimization Algorithm, HO&#xff09;。 2.算法原理 2.1算法思想 …

動態IP的應用場景

動態IP適用于網絡設備規模較小、需要靈活連接網絡、經濟條件有限或者需要臨時建立網絡的場景。

【C++】AVL

提示&#xff1a;文章寫完后&#xff0c;目錄可以自動生成&#xff0c;如何生成可參考右邊的幫助文檔 目錄 前言 一、AVL 樹 1.1、AVL樹的概念 1.2、AVL樹節點的定義 1.3、AVL樹的插入 1.4、AVL樹的旋轉 1.4.1、新節點插入較高左子樹的左側---左左&#xff1a;右單旋 1…