网页版Java五子棋项目(二)前后端实现用户的登录和注册功能【用户模块】
在用户模块我们要清楚要完成的任务 一、MyBatis后端操作数据库 1. 需要在数据库创建用户数据库 1. 用户id 2. 用户名 3. 密码 4. 天梯积分 5. 总场数 6. 获胜场数
2. 创建用户类User
3. 用MyBatis操作数据库 1. 连接数据库(application.yml连接数据库)
2. 创建UserMapper的Java接口(interface UserMapper) 创建接口,在UserMapper.xml实现 在model中创建 需要实现@Mapper注释
3. 创建UserMapper.xml 实现数据库操作 实现具体数据库操作 利用标签 mapper标签地址要对应好 不同操作 标签不同
二、约定前后端接口 1. 登录接口 前端发送post请求,具体内容是直接对应的 所以后端的参数也是对应的,然后后端返回一个用户类 1. 后端通过前端传的用户名,查询数据库 2. 如果数据库为空,返回一个新的 用户类 3. 否则,把Session置为true 4. 然后返回用户类
2. 注册接口 前端POST请求,参数是一一对应 后端参数接受一个一一对应 1. 创建一个User类 2. 调用userMapper插入 如果创建重复 则抛出异常 返回一个新的User
3. 从服务器获取当前登录的信息 前端GET请求 后端 1. 判断用户是否Session中 2. 查询数据库 返回对应类 如果没有在则返回一个新的user
4. UserAPI
三、实现前端页面
在用户模块我们要清楚要完成的任务
一、MyBatis后端操作数据库
1. 需要在数据库创建用户数据库
1. 用户id
2. 用户名
3. 密码
4. 天梯积分
5. 总场数
6. 获胜场数
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 , '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 ) ;
2. 创建用户类User
和数据库的数据一一对应
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;
}
}
3. 用MyBatis操作数据库
1. 连接数据库(application.yml连接数据库)
这个可以直接赋值代码
spring :
datasource :
url : jdbc: mysql: //127.0.0.1: 3306/java_gobang? characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8
username : root
password : 123456
driver-class-name : com.mysql.cj.jdbc.Driver
mybatis :
mapper-locations : classpath: mapper/**Mapper.xml
logging :
pattern :
console : "[%-5level] - %msg%n"
2. 创建UserMapper的Java接口(interface UserMapper)
创建接口,在UserMapper.xml实现
在model中创建
需要实现@Mapper注释
package com. example. java_gobang. model ;
import org. apache. ibatis. annotations. Mapper ;
@Mapper
public interface UserMapper {
void insert ( User user) ;
User selectByName ( String username) ;
void userWin ( int userId) ;
void userLose ( int userId) ;
}
3. 创建UserMapper.xml 实现数据库操作
实现具体数据库操作
利用标签
mapper标签地址要对应好
不同操作 标签不同
<?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>
< update id = " userWin" >
update user set totalCount = totalCount + 1, winCount = winCount + 1, score = score + 30
where userId = #{userId}
</ update>
< update id = " userLose" >
update user set totalCount = totalCount + 1, score = score - 30
where userId = #{userId}
</ update>
</ mapper>
二、约定前后端接口
1. 登录接口
前端发送post请求,具体内容是直接对应的
所以后端的参数也是对应的,然后后端返回一个用户类
1. 后端通过前端传的用户名,查询数据库
2. 如果数据库为空,返回一个新的 用户类
3. 否则,把Session置为true
4. 然后返回用户类
@PostMapping ( "/login" )
@ResponseBody
public Object login ( String username, String password, HttpServletRequest req) {
User user = userMapper. selectByName ( username) ;
System . out. println ( "[login] username=" + username) ;
if ( user == null || ! user. getPassword ( ) . equals ( password) ) {
System . out. println ( "登录失败!" ) ;
return new User ( ) ;
}
HttpSession httpSession = req. getSession ( true ) ;
httpSession. setAttribute ( "user" , user) ;
return user;
}
2. 注册接口
前端POST请求,参数是一一对应
后端参数接受一个一一对应
1. 创建一个User类
2. 调用userMapper插入
如果创建重复 则抛出异常 返回一个新的User
@PostMapping ( "/register" )
@ResponseBody
public Object register ( String username, String password) {
try {
User user = new User ( ) ;
user. setUsername ( username) ;
user. setPassword ( password) ;
userMapper. insert ( user) ;
return user;
} catch ( org. springframework. dao. DuplicateKeyException e) {
User user = new User ( ) ;
return user;
}
}
3. 从服务器获取当前登录的信息
前端GET请求
后端
1. 判断用户是否Session中
2. 查询数据库 返回对应类
如果没有在则返回一个新的user
@GetMapping ( "/userInfo" )
@ResponseBody
public Object getUserInfo ( HttpServletRequest req) {
try {
HttpSession httpSession = req. getSession ( false ) ;
User user = ( User ) httpSession. getAttribute ( "user" ) ;
User newUser = userMapper. selectByName ( user. getUsername ( ) ) ;
return newUser;
} catch ( NullPointerException e) {
return new User ( ) ;
}
}
4. UserAPI
package com. example. java_gobang. api ;
import com. example. java_gobang. model. User ;
import com. example. java_gobang. model. UserMapper ;
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 ;
import javax. annotation. Resource ;
import javax. servlet. http. HttpServletRequest ;
import javax. servlet. http. HttpSession ;
@RestController
public class UserAPI {
@Resource
private UserMapper userMapper;
@PostMapping ( "/login" )
@ResponseBody
public Object login ( String username, String password, HttpServletRequest req) {
User user = userMapper. selectByName ( username) ;
System . out. println ( "[login] username=" + username) ;
if ( user == null || ! user. getPassword ( ) . equals ( password) ) {
System . out. println ( "登录失败!" ) ;
return new User ( ) ;
}
HttpSession httpSession = req. getSession ( true ) ;
httpSession. setAttribute ( "user" , user) ;
return user;
}
@PostMapping ( "/register" )
@ResponseBody
public Object register ( String username, String password) {
try {
User user = new User ( ) ;
user. setUsername ( username) ;
user. setPassword ( password) ;
userMapper. insert ( user) ;
return user;
} catch ( org. springframework. dao. DuplicateKeyException e) {
User user = new User ( ) ;
return user;
}
}
@GetMapping ( "/userInfo" )
@ResponseBody
public Object getUserInfo ( HttpServletRequest req) {
try {
HttpSession httpSession = req. getSession ( false ) ;
User user = ( User ) httpSession. getAttribute ( "user" ) ;
User newUser = userMapper. selectByName ( user. getUsername ( ) ) ;
return newUser;
} catch ( NullPointerException e) {
return new User ( ) ;
}
}
}
三、实现前端页面
1. 登录页面
<! DOCTYPE html >
< html lang = " en" >
< head>
< meta charset = " UTF-8" >
< meta http-equiv = " X-UA-Compatible" content = " IE=edge" >
< meta name = " viewport" content = " width=device-width, initial-scale=1.0" >
< title> 登录</ title>
< link rel = " stylesheet" href = " css/common.css" >
< link rel = " stylesheet" href = " css/login.css" >
</ 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>
< div class = " row" >
< button id = " submit" > 提交</ button>
</ div>
</ div>
</ div>
< 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 ( ) {
$. ajax ( {
type : 'post' ,
url : '/login' ,
data : {
username : usernameInput. value,
password : passwordInput. value,
} ,
success : function ( body ) {
if ( body && body. userId > 0 ) {
alert ( "登录成功!" ) ;
location. assign ( '/game_hall.html' ) ;
} else {
alert ( "登录失败!" ) ;
}
} ,
error : function ( ) {
alert ( "登录失败!" ) ;
}
} ) ;
}
</ script>
</ body>
</ html>
2. 注册页面
<! DOCTYPE html >
< html lang = " en" >
< head>
< meta charset = " UTF-8" >
< meta http-equiv = " X-UA-Compatible" content = " IE=edge" >
< meta name = " viewport" content = " width=device-width, initial-scale=1.0" >
< title> 注册</ title>
< link rel = " stylesheet" href = " css/common.css" >
< link rel = " stylesheet" href = " css/login.css" >
</ 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>
< div class = " row" >
< button id = " submit" > 提交</ button>
</ div>
</ div>
</ div>
< 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 ( ) {
$. 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 ( "注册失败!" ) ;
}
} ) ;
}
</ script>
</ body>
</ html>