添加用户注册/add sql

This commit is contained in:
2023-06-30 00:36:31 +08:00
parent 5aee01812f
commit 2c095dfba0
4 changed files with 345 additions and 4 deletions

158
sql/hellogithub.sql Normal file
View File

@@ -0,0 +1,158 @@
/*
Navicat Premium Data Transfer
Source Server : MySQL
Source Server Type : MySQL
Source Server Version : 80031 (8.0.31)
Source Host : localhost:3306
Source Schema : hellogithub
Target Server Type : MySQL
Target Server Version : 80031 (8.0.31)
File Encoding : 65001
Date: 30/06/2023 00:34:31
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for admin
-- ----------------------------
DROP TABLE IF EXISTS `admin`;
CREATE TABLE `admin` (
`adminId` int NOT NULL AUTO_INCREMENT COMMENT '管理员ID',
`adminName` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '管理员名',
`adminPassword` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '管理员密码',
`isValid` int NULL DEFAULT NULL COMMENT '是否有效(0/1)',
PRIMARY KEY (`adminId`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '管理员表' ROW_FORMAT = DYNAMIC;
-- ----------------------------
-- Records of admin
-- ----------------------------
-- ----------------------------
-- Table structure for article
-- ----------------------------
DROP TABLE IF EXISTS `article`;
CREATE TABLE `article` (
`articleId` int NOT NULL AUTO_INCREMENT COMMENT '文章ID',
`userId` int NULL DEFAULT NULL COMMENT '用户ID',
`articleContent` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '文章内容',
`publishTime` datetime NULL DEFAULT NULL COMMENT '发布时间',
`isValid` int NULL DEFAULT NULL COMMENT '是否有效',
PRIMARY KEY (`articleId`) USING BTREE,
INDEX `userId_article`(`userId` ASC) USING BTREE,
CONSTRAINT `userId_article` FOREIGN KEY (`userId`) REFERENCES `user` (`userId`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '文章表' ROW_FORMAT = DYNAMIC;
-- ----------------------------
-- Records of article
-- ----------------------------
-- ----------------------------
-- Table structure for category
-- ----------------------------
DROP TABLE IF EXISTS `category`;
CREATE TABLE `category` (
`categoryId` int NOT NULL AUTO_INCREMENT COMMENT '标签ID',
`category` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '标签内容',
`isValid` int NULL DEFAULT NULL COMMENT '是否有效0/1',
PRIMARY KEY (`categoryId`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '标签表' ROW_FORMAT = DYNAMIC;
-- ----------------------------
-- Records of category
-- ----------------------------
-- ----------------------------
-- Table structure for comment
-- ----------------------------
DROP TABLE IF EXISTS `comment`;
CREATE TABLE `comment` (
`commentId` int NOT NULL AUTO_INCREMENT COMMENT '评论ID',
`userId` int NULL DEFAULT NULL COMMENT '用户ID',
`projectId` int NULL DEFAULT NULL COMMENT '项目ID',
`content` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '评论内容',
`isUsed` int NULL DEFAULT NULL COMMENT '是否使用过',
`commentTime` datetime NULL DEFAULT NULL COMMENT '评论时间',
`isValid` int NULL DEFAULT NULL COMMENT '是否有效',
PRIMARY KEY (`commentId`) USING BTREE,
INDEX `userId_comment`(`userId` ASC) USING BTREE,
INDEX `projectId_comment`(`projectId` ASC) USING BTREE,
CONSTRAINT `projectId_comment` FOREIGN KEY (`projectId`) REFERENCES `project` (`projectId`) ON DELETE RESTRICT ON UPDATE RESTRICT,
CONSTRAINT `userId_comment` FOREIGN KEY (`userId`) REFERENCES `project` (`userId`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '评论表' ROW_FORMAT = DYNAMIC;
-- ----------------------------
-- Records of comment
-- ----------------------------
-- ----------------------------
-- Table structure for project
-- ----------------------------
DROP TABLE IF EXISTS `project`;
CREATE TABLE `project` (
`projectId` int NOT NULL AUTO_INCREMENT COMMENT '项目ID',
`userId` int NULL DEFAULT NULL COMMENT '用户ID',
`projectUrl` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '项目地址',
`projectIco` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '项目图标',
`projectTitle` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '项目标题',
`projectDescription` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '项目描述',
`startNum` int NULL DEFAULT NULL COMMENT '点赞数',
`submitTime` datetime NULL DEFAULT NULL COMMENT '提交时间',
`categoryId` int NULL DEFAULT NULL COMMENT '标签ID',
`isValid` int NULL DEFAULT NULL COMMENT '是否有效(0/1)',
`fileAddress` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '项目文件地址',
`periodicals` int NULL DEFAULT NULL COMMENT '期刊',
PRIMARY KEY (`projectId`) USING BTREE,
INDEX `userId`(`userId` ASC) USING BTREE,
CONSTRAINT `userId` FOREIGN KEY (`userId`) REFERENCES `user` (`userId`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '项目表' ROW_FORMAT = DYNAMIC;
-- ----------------------------
-- Records of project
-- ----------------------------
-- ----------------------------
-- Table structure for project_category
-- ----------------------------
DROP TABLE IF EXISTS `project_category`;
CREATE TABLE `project_category` (
`id` int NOT NULL AUTO_INCREMENT COMMENT 'id',
`categoryId` int NULL DEFAULT NULL COMMENT '标签ID',
`projectId` int NULL DEFAULT NULL COMMENT '项目ID',
PRIMARY KEY (`id`) USING BTREE,
INDEX `categoryId`(`categoryId` ASC) USING BTREE,
INDEX `projectId`(`projectId` ASC) USING BTREE,
CONSTRAINT `categoryId` FOREIGN KEY (`categoryId`) REFERENCES `category` (`categoryId`) ON DELETE RESTRICT ON UPDATE RESTRICT,
CONSTRAINT `projectId` FOREIGN KEY (`projectId`) REFERENCES `project` (`projectId`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '项目标签中间表' ROW_FORMAT = DYNAMIC;
-- ----------------------------
-- Records of project_category
-- ----------------------------
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`userId` int NOT NULL AUTO_INCREMENT COMMENT '用户ID',
`userName` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '用户名',
`userPassword` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '密码',
`creatTime` datetime NULL DEFAULT NULL COMMENT '创建时间',
`isValid` int NULL DEFAULT NULL COMMENT '是否有效(0/1)',
`projectNum` int NULL DEFAULT NULL COMMENT '提交的项目总数',
`searchHistory` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '搜索历史',
PRIMARY KEY (`userId`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '用户表' ROW_FORMAT = DYNAMIC;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, '666', '666', '2023-06-29 22:43:22', 1, 1, NULL);
SET FOREIGN_KEY_CHECKS = 1;

View File

@@ -4,21 +4,23 @@ import com.hellogithub.entity.UserEntity;
import com.hellogithub.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
/**
* 用户Dao层
* */
*/
public class UserDao {
private UserEntity userEntity=new UserEntity();
private UserEntity userEntity = new UserEntity();
/**
* 用户登录
*
* @param userName
* @param password
* */
public UserEntity UserLogin(String userName,String password){
*/
public UserEntity UserLogin(String userName, String password) {
ResultSet resultSet = null;
PreparedStatement preparedStatement = null;
Connection connection = null;
@@ -45,4 +47,70 @@ public class UserDao {
JdbcUtils.closeConnection(resultSet, preparedStatement, connection);
}
}
/**
* 用户注册
*
* @param userName
* @param userPwd
*/
public int userRegister(String userName, String userPwd) {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = JdbcUtils.getConnection();
// sql语句写的操作 ----加上事务
JdbcUtils.beginTransaction(connection); // 开启事务
String insertSql = "INSERT INTO `user` (`userId`, `userName`, `userPassword`,`creatTime`,`isValid`) VALUES (null, ?, ?,?,1);";
preparedStatement = connection.prepareStatement(insertSql);
preparedStatement.setString(1, userName);
preparedStatement.setString(2, userPwd);
Date time= new java.sql.Date(new java.util.Date().getTime());
preparedStatement.setDate(3, time);
int result = preparedStatement.executeUpdate();
// 代码执行没有问题的情况下 则会提交数据
JdbcUtils.commitTransaction(connection); // 提交事务
return result;
} catch (Exception e) {
// 程序代码报错之后 是需要回滚事务
e.printStackTrace();
JdbcUtils.rollBackTransaction(connection);// 回滚事务
return 0;
} finally {
JdbcUtils.closeConnection(preparedStatement, connection);
}
}
/**
* 通过用户名查询
*
* @param userName
*/
public UserEntity findByUserName(String userName) {
ResultSet resultSet = null;
PreparedStatement preparedStatement = null;
Connection connection = null;
try {
connection = JdbcUtils.getConnection();
String loginSql = "select * from user where userName=?";
preparedStatement = connection.prepareStatement(loginSql);
preparedStatement.setString(1, userName);
resultSet = preparedStatement.executeQuery();
if (!resultSet.next()) { // 查询不到用户数据
return null;
}
// 将db中数据 返回给客户端 查询到数据
Integer id = resultSet.getInt(1);
String dbUserName = resultSet.getString(2);
String dbUserPwd = resultSet.getString(3);
UserEntity mayiktUserEntity = new UserEntity(dbUserName, dbUserPwd);
return mayiktUserEntity;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
JdbcUtils.closeConnection(resultSet, preparedStatement, connection);
}
}
}

View File

@@ -8,7 +8,27 @@ import com.hellogithub.entity.UserEntity;
* */
public class UserService {
private UserDao userDao=new UserDao();
/**
* 用户登录
* @param userName
* @param password
* */
public UserEntity UserLogin(String userName,String password){
return userDao.UserLogin(userName,password);
}
/**
* 用户注册
* @param userName
* @param userPwd
* */
public int userRegister(String userName, String userPwd) {
return userDao.userRegister(userName,userPwd);
}
/**
* 通过用户名查询
* @param userName
* */
public UserEntity findByUserName(String userName) {
return userDao.findByUserName(userName);
}
}

View File

@@ -0,0 +1,95 @@
package com.hellogithub.servlet;
import com.alibaba.fastjson.JSONObject;
import com.hellogithub.entity.UserEntity;
import com.hellogithub.service.UserService;
import com.hellogithub.utils.RandomValidateCode;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
@WebServlet("/userRegister")
public class UserRegisterServlet extends HttpServlet {
private UserService userService = new UserService();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html; charset=utf-8");
// 设置响应头允许ajax跨域访问
String curOrigin = req.getHeader("Origin");
resp.setHeader("Access-Control-Allow-Origin", curOrigin == null ? "true" : curOrigin);
resp.setHeader("Access-Control-Allow-Credentials", "true");
resp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, HEAD");
resp.setHeader("Access-Control-Max-Age", "3600");
resp.setHeader("Access-Control-Allow-Headers", "access-control-allow-origin, authority, content-type, version-info, X-Requested-With");
resp.setContentType("application/json;charset=UTF-8");
PrintWriter writer = resp.getWriter();
String userName = req.getParameter("username");
if (StringUtils.isEmpty(userName)) {
setResultError("用户名称不能够是为空", writer);
return;
}
String userPwd = req.getParameter("password");
// 参数验证
if (StringUtils.isEmpty(userPwd)) {
//转发到错误页面
setResultError("密码不能够是为空", writer);
return;
}
// 比较图形验证码
String userCode = req.getParameter("code"); // 用户输入的图形验证码
// 从session中获取图形验证码
HttpSession session = req.getSession();
String sessionCode = (String) session.getAttribute(RandomValidateCode.RANDOMVALIDATECODE);
if (!sessionCode.equalsIgnoreCase(userCode)) {
setResultError("图形验证码不正确,请重新输入!", writer);
return;
}
// 用户注册之前根据用户名称查询该用户是否存在如果不存在的情况下才可以注册 如果存在的话就无法注册
UserEntity userEntity = userService.findByUserName(userName);
if (userEntity != null) {
setResultError("用户名: " + userName + "已被注册!", writer);
return;
}
//用户数据注册
int register = userService.userRegister(userName, userPwd);
if (register <= 0) {
// 注册失败了 //转发到错误页面
setResultError("注册失败!", writer);
return;
}
setResultOK("注册成功!", writer);
}
public void setResult(Integer code, String msg, PrintWriter writer) {
HashMap<String, Object> result = new HashMap<>();
result.put("code", code);
result.put("msg", msg);
String jsonString = JSONObject.toJSONString(result);
writer.println(jsonString);
writer.close();
}
public void setResultError(String msg, PrintWriter writer) {
setResult(500, msg, writer);
}
public void setResultOK(String msg, PrintWriter writer) {
setResult(200, msg, writer);
}
}