还存在的问题:
当校验不通过时 , 表单依旧能够提交
之后使用VUE 的 axios 结合 promise 处理
注册提交前校验用户名是否占用功能
使用 后端 传递JSON 的方式 原因:
- 解决响应乱码问题
- 规范响应信息格式
- 后端响应信息建立统一的格式:
- 响应一个JSON
{
“code”:“200 505… 就是自定义的业务状态码 用于说明这次的业务请求状态”
“message”: “针对业务状态码的补充说明/描述”
“data”:“{}” 本次响应的数据 成功/不成功List
…
…
}
主要代码:
<script>
function checkUsername() {
var usernameReg = /^[a-zA-Z0-9]{5,10}$/
var usernameInput = document.getElementById("usernameInput")
var username = usernameInput.value
var usernameMsg = document.getElementById("usernameMsg")
if (!usernameReg.test(username)) {
usernameMsg.innerText = "格式有误"
return false
}
// Ajax 验证 用户名 是否已被占用
let request = new XMLHttpRequest();
// 设置回调函数 对响应回来的数据进行处理
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200) {
// usernameMsg.innerText = request.responseText;
//接收 服务端响应回来的JSON
let result = JSON.parse(request.responseText);
// 返回的code 业务码不为200 即失败 用户名已存在
if (result.code != 200) {
usernameMsg.innerText = "不可用"
}
}
}
// 设置请求方式 以及 请求目标资源的路径
request.open("GET", "/user/checkUsernameUsed?username=" + username)
request.send();
usernameMsg.innerText = "OK"
return true
}
script>
package com.doug.wake.common;
/**
* 业务含义和状态码对应关系的枚举
*
*/
public enum ResultCodeEnum {
/**
* 成功 200
*/
SUCCESS(200,"success"),
USERNAME_ERROR(501,"usernameError"),
PASSWORD_ERROR(503,"passwordError"),
NOTLOGIN(504,"notLogin"),
USERNAME_USED(505,"userNameUsed")
;
private Integer code;
private String message;
private ResultCodeEnum(Integer code, String message) {
this.code = code;
this.message = message;
}
public Integer getCode() {
return code;
}
public String getMessage() {
return message;
}
}
package com.doug.wake.common;
/**
* 全局统一响应的JSON格式处理类
*/
public class Result<T> {
// 返回码
private Integer code;
// 返回消息
private String message;
// 返回数据
private T data;
public Result() {
}
// 返回数据
protected static <T> Result<T> build(T data) {
Result<T> result = new Result<T>();
if (data != null) {
result.setData(data);
}
return result;
}
public static <T> Result<T> build(T body, Integer code, String message) {
Result<T> result = build(body);
result.setCode(code);
result.setMessage(message);
return result;
}
public static <T> Result<T> build(T body, ResultCodeEnum resultCodeEnum) {
Result<T> result = build(body);
result.setCode(resultCodeEnum.getCode());
result.setMessage(resultCodeEnum.getMessage());
return result;
}
/**
* 操作成功
*
* @param data baseCategory1List
* @param
* @return
*/
public static <T> Result<T> ok(T data) {
Result<T> result = build(data);
return build(data, ResultCodeEnum.SUCCESS);
}
public Result<T> message(String msg) {
this.setMessage(msg);
return this;
}
public Result<T> code(Integer code) {
this.setCode(code);
return this;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
用于JSON对象转换
package com.doug.wake.util;
import com.doug.wake.common.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
/**
* JSON对象转换工具类
*/
public class WebUtil {
private static ObjectMapper objectMapper;
// 初始化objectMapper
static {
objectMapper = new ObjectMapper();
// 设置JSON和Object转换时的时间日期格式
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
}
/**
* 从请求中获取JSON串并转换为Object
*/
public static <T> T readJson(HttpServletRequest request, Class<T> clazz) {
T t = null;
BufferedReader reader = null;
try {
reader = request.getReader();
StringBuffer buffer = new StringBuffer();
String line = null;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
t = objectMapper.readValue(buffer.toString(), clazz);
} catch (IOException e) {
throw new RuntimeException(e);
}
return t;
}
/**
* 将Result对象转换成JSON串并放入响应对象
* @param response
* @param result
*/
public static void writeJson(HttpServletResponse response, Result result) {
response.setContentType("application/json;charset=UTF-8");
try {
String json = objectMapper.writeValueAsString(result);
response.getWriter().write(json);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
/**
* 用于处理前端Ajax传递的用户名 是否被占用的判断
*
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void checkUsernameUsed(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
SysUser user = userService.findUserByUsername(username);
//String info = "用户名可以使用!";
//if (null != user) {
// info = "用户名已存在!";
//}
//resp.getWriter().write(info);
Result result = Result.ok(null);
if (null != user) {
result = Result.build(null, ResultCodeEnum.USERNAME_USED);
}
//将result对象转换为JSON响应给客户端
WebUtil.writeJson(resp, result);
}
regist.html页面完整代码 :
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<style>
.ht {
text-align: center;
color: cadetblue;
font-family: 幼圆;
}
.tab {
width: 500px;
border: 5px solid cadetblue;
margin: 0px auto;
border-radius: 5px;
font-family: 幼圆;
}
.ltr td {
border: 1px solid powderblue;
}
.ipt {
border: 0px;
width: 50%;
}
.btn1 {
border: 2px solid powderblue;
border-radius: 4px;
width: 60px;
background-color: antiquewhite;
}
.msg {
color: gold;
}
.buttonContainer {
text-align: center;
}
style>
<script>
function checkUsername() {
var usernameReg = /^[a-zA-Z0-9]{5,10}$/
var usernameInput = document.getElementById("usernameInput")
var username = usernameInput.value
var usernameMsg = document.getElementById("usernameMsg")
if (!usernameReg.test(username)) {
usernameMsg.innerText = "格式有误"
return false
}
// Ajax 验证 用户名 是否已被占用
let request = new XMLHttpRequest();
// 设置回调函数 对响应回来的数据进行处理
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200) {
// usernameMsg.innerText = request.responseText;
let result = JSON.parse(request.responseText);
if (result.code != 200) {
usernameMsg.innerText = "不可用"
}
}
}
// 设置请求方式 以及 请求目标资源的路径
request.open("GET", "/user/checkUsernameUsed?username=" + username)
request.send();
usernameMsg.innerText = "OK"
return true
}
function checkUserPwd() {
var userPwdReg = /^\d{6}$/
var userPwdInput = document.getElementById("userPwdInput")
var userPwd = userPwdInput.value
var userPwdMsg = document.getElementById("userPwdMsg")
if (!userPwdReg.test(userPwd)) {
userPwdMsg.innerText = "格式有误"
return false
}
userPwdMsg.innerText = "OK"
return true
}
function checkReUserPwd() {
var userPwdReg = /^\d{6}$/
// 再次输入的密码的格式
var reUserPwdInput = document.getElementById("reUserPwdInput")
var reUserPwd = reUserPwdInput.value
var reUserPwdMsg = document.getElementById("reUserPwdMsg")
if (!userPwdReg.test(reUserPwd)) {
reUserPwdMsg.innerText = "格式有误"
return false
}
// 获得上次密码,对比两次密码是否一致
var userPwdInput = document.getElementById("userPwdInput")
var userPwd = userPwdInput.value
if (reUserPwd != userPwd) {
reUserPwdMsg.innerText = "两次密码不一致"
return false
}
reUserPwdMsg.innerText = "OK"
return true
}
function checkForm() {
var flag1 = checkUsername()
var flag2 = checkUserPwd()
var flag3 = checkReUserPwd()
return flag1 && flag2 && flag3
}
script>
head>
<body>
<h1 class="ht">欢迎使用日程管理系统h1>
<h3 class="ht">请注册h3>
<form method="post" action="/user/regist" onsubmit="return checkForm()">
<table class="tab" cellspacing="0px">
<tr class="ltr">
<td>请输入账号td>
<td>
<input class="ipt" id="usernameInput" type="text" name="username" onblur="checkUsername()">
<span id="usernameMsg" class="msg">span>
td>
tr>
<tr class="ltr">
<td>请输入密码td>
<td>
<input class="ipt" id="userPwdInput" type="password" name="userPwd" onblur="checkUserPwd()">
<span id="userPwdMsg" class="msg">span>
td>
tr>
<tr class="ltr">
<td>确认密码td>
<td>
<input class="ipt" id="reUserPwdInput" type="password" onblur="checkReUserPwd()">
<span id="reUserPwdMsg" class="msg">span>
td>
tr>
<tr class="ltr">
<td colspan="2" class="buttonContainer">
<input class="btn1" type="submit" value="注册">
<input class="btn1" type="reset" value="重置">
<button class="btn1"><a href="login.html">去登录a>button>
td>
tr>
table>
form>
body>
html>