1.準備工作
1.1.前端頁面展示?
1.2 數據庫的建立?
我們通過注冊頁面,考慮如何設計用戶表數據庫。
- 用戶id,userId
- 用戶名,唯一,username
- 用戶密碼,password(包括密碼和確認密碼ensurePssword【數據庫沒有該字段】)
- 同時還需要考慮是否需要將圖片和用戶進行分離
????????????????//我考慮的是將其合并在一起
????????????????//這樣做的好處是直接和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 測試
注冊成功!!!