注册功能实现分析
目录
一、AppConfig.java
二、register.html
三、UserDto.java
四、UserController.java
五、UserMapper.xml
六、运行结果
一、AppConfig.java
@Configuration
public class AppConfig implements WebMvcConfigurer {
//统一视图跳转
@Override
public void addViewControllers(ViewControllerRegistry registry){
//访问路径为http://localhost:8080/时,那么就是访问login文件夹下的login.html页面
registry.addViewController("/").setViewName("login/login");
registry.addViewController("/login.html").setViewName("login/login");
registry.addViewController("/register.html").setViewName("login/register");
}
}
二、register.html
js表单校验、ajax验证用户名是否被占用、ajax提交表单
<form id="form100" action="login.html" method="post" class="reg-form">
<p><label for="userName"><em>*</em>用户名:</label>
<input name="userName" type="text" class="input-txt" id="userName" autocomplete="off" size="43"
onblur="checkUserName(this)"/>
<span id="userNameError"></span>
</p>
<p><label for="password"><em>*</em>密码:</label>
<input name="password" type="password" class="input-txt" id="password" autocomplete="off" size="43"
onblur="checkPassword(this)"/>
<span id="passwordError"></span>
</p>
<p><label for="surePassword"><em>*</em>确认密码:</label>
<input name="surePassword" type="password" class="input-txt" id="surePassword" autocomplete="off"
size="43"
onblur="checkSurePassword(this)"/>
<span id="surePasswordError"></span>
</p>
<p><label for="email"><em>*</em>邮箱:</label>
<input name="email" type="text" class="input-txt" id="email" size="43"
onblur="checkEmail(this)">
<span id="emailError"></span>
</p>
<p class="chcek-rule"><input name="agree" type="checkbox" value="1" checked/>
<span class="fl">我同意</span><a href="#" target="_blank">《驴友网服务公约》</a>
</p>
<a class="regbtn" id="submit" href="javascript:void(0);" hidefocus="true"
onclick="register()">立即注册</a>
</form>
<script type="text/javascript" th:src="@{webjars/jquery/3.6.1/jquery.js}"></script>
<script>
function checkUserName(userNameObj) {
let userName = $(userNameObj).val();
if (userName.length < 3) {
$(userNameObj).next().text("用戶名长度不能小于3");
$(userNameObj).next().css("color", "red");
return false;
} else {
$.ajax({
type: "post",
url: "/user/checkUserName",
data: {"username": userName},
async: "false",
dataType: "json",
success: function (msg) {
if (!msg) {
$(userNameObj).next().text("用户名已占用");
$(userNameObj).next().css("color", "red");
return false;
}
},
error: function () {
alert("网络不可用")
}
})
}
$(userNameObj).next().text("用户名校验通过")
$(userNameObj).next().css("color", "green");
return true;
}
function checkPassword(passwordObj) {
let password = $(passwordObj).val();
if (password.length < 6 || password.length >= 16) {
$(passwordObj).next().text("密码只能是6-16位之间");
$(passwordObj).next().css("color", "red");
return false;
}
$(passwordObj).next().text("密码校验通过")
$(passwordObj).next().css("color", "green");
return true;
}
function checkSurePassword(surePasswordObj) {
let surePassword = $(surePasswordObj).val();
if (surePassword.length < 6 || surePassword.length >= 16) {
$(surePasswordObj).next().text("重复密码只能是6-16位之间");
$(surePasswordObj).next().css("color", "red");
return false;
}
let password = $("#password").val();
if (surePassword != password) {
$(surePasswordObj).next().text("密码和重复密码不一致");
$(surePasswordObj).next().css("color", "red");
return false;
}
$(surePasswordObj).next().text("重复密码校验通过")
$(surePasswordObj).next().css("color", "green");
return true;
}
function checkEmail(emailObj) {
let reg = /^[a-zA-Z0-9]+([-_.][A-Za-zd]+)*@([a-zA-Z0-9]+[-.])+[A-Za-zd]{2,5}$/;
let email = $(emailObj).val();
if (!reg.test(email)) {
$(emailObj).next().text("邮箱格式不正确");
$(emailObj).next().css("color", "red");
return false;
}
$(emailObj).next().text("邮箱校验通过")
$(emailObj).next().css("color", "green");
return true;
}
function register() {
let userNameObj = document.getElementById("userName");
let passwordObj = document.getElementById("password");
let surePasswordObj = document.getElementById("surePassword");
let emailObj = document.getElementById("email");
if (checkUserName(userNameObj)
&& checkPassword(passwordObj) && checkSurePassword(surePasswordObj)
&& checkEmail(emailObj)) {
let $data = $("#form100").serialize();
console.log($data);
$.ajax({
type: "post",
url: "/user/register",
data: $data,
dataType: "json",
success: function (msg) {
if (msg) {
alert("注册成功");
location.href = "/login.html";
} else {
alert("注册失败")
}
},
error: function () {
alert("网络不可用")
}
})
}
}
</script>
三、UserDto.java
/**
* @description: 注册参数实体
**/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserDto {
private String userName; //注册的用户名
private String password; //注册的密码
private String email; //注册的邮箱
}
四、UserController.java
/**
* @description: 用户相关的控制层
**/
@Controller//标记控制层,把当前类的对象交给容器管理
//映射路径(访问路径,可以声明在类和方法上),只要访问此类中的资源,一级路径必须是user
@RequestMapping("/user")
@Slf4j //日志框架
public class UserController {
@Autowired//根据类型自动注入对象
@Qualifier("userService")//如果指定注入的对象,使用Qualifier注解
private IUserService userService;
//登录
@RequestMapping("login")
public String login(String username, String password, Model model, HttpSession session) {
log.info("login方法入参:username={},password={}", username, password); //日志信息打印
//1.接收请求中的参数(view-controller):方法的入参直接获取(页面输入的username和password)
//2.处理数据
//(1)创建UserServiceImpl的对象 --- 成员变量自动注入
//(2)调用service中的方法 参数:username password 返回值:UserEntity
UserEntity user = userService.login(username, password);
//3.保存数据(controller-view)并跳转页面
String url;
//(1)判断登录是否成功
if (user != null) {
//(2)成功 1.把数据保存到session中 2.跳转页面到index.html
session.setAttribute("USER", user);
if (user.getRole() == 1) {
url = "index";
} else {
url = "/admin/index";
}
} else {
//(3)失败 1.把异常信息保存到model中 2.跳转到login.html
model.addAttribute("msg", "登录名或者密码错误");
url = "/login/login";
}
//经过视图解析器,最终路径解析为 前缀(/templates/)+url+后缀(.html)
return url;
}
//验证用户名是否存在
@RequestMapping("/checkUserName")
public @ResponseBody
boolean checkUserName(String username) {
System.out.println("==============" + username);
//1.接收页面参数---方法入参 username
//2.处理数据,调用service中验证用户名是否注册过的方法 参数:userName 返回值:boolean
return userService.checkUserName(username);
}
//注册
@RequestMapping("/register")
public @ResponseBody
boolean register(UserDto userDto) {
System.out.println("===============" + userDto);
//1.接收页面参数--方法入参 UserDto
//2.调用service中注册的方法 参数:UserDto 返回值:boolean
return userService.register(userDto);
}
}
五、UserMapper.xml
注:IUservice接口、UserServerImpl类、UserMapper接口略
<?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,namespace的值设置成DAO接口名,这样就能够保证能够匹配DAO接口-->
<mapper namespace="com.shenu.travelsys.mapper.UserMapper">
<!--登录
select:标识查询
id:和接口中抽象方法名必须一致,调用方法实际执行当前标签的sql语句
#{username}:#占位符,把抽象方法中的参数赋值到sql语句的条件中
resultType: 查询结果自动映射到指定的类型中
-->
<select id="login" resultType="UserEntity">
select *
from t_user
where username = #{username}
and `password` = #{password}
</select>
<!--验证用户名是否存在-->
<select id="checkUserName" resultType="UserEntity">
select userid
from t_user
where username = #{username}
</select>
<!--注册-->
<insert id="register">
insert into t_user(username, password, email, status, role)
values (#{userName}, #{password}, #{email}, 1, 1)
</insert>
</mapper>