简单登录+注册+验证码页面 前后端交互(前端加后端 AJAX局部判断 DRuid连接池 MySQL DBUtils)
简单登录+注册+验证码页面 前后端交互(前端加后端 AJAX局部判断 DRuid连接池 MySQL DBUtils)
文章目录
问题
使用axios post 提交数据,后台获取不到
解决
【用 URLSearchParams 传递参数】
let param = new URLSearchParams()
param.append('username', 'admin')
param.append('pwd', 'admin')
axios({
method: 'post',
url: '/api/lockServer/search',
data: param
})
需要注意的是: `URLSearchParams` 不支持所有的浏览器,但是总体的支持情况还是 OK 的,所以优先推荐这种简单直接的解决方案
结构


效果图
数据库

注册页面





登录页面



登录后页面

代码
后端登陆
- 工具类mysql
package Login;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.apache.commons.dbutils.QueryRunner;
import javax.sql.DataSource;
import java.io.InputStream;
import java.util.Properties;
public class DBCon {
public QueryRunner con() {
InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("druid.properties");
Properties properties = new Properties(); DataSource dataSource = null;
try {
properties.load(resourceAsStream);
dataSource = DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
QueryRunner queryRunner = new QueryRunner(dataSource);
return queryRunner;
}
}
- 用户类
package Login;
public class User {
private String username;
private String password;
public User() {
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
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;
}
}
- 登录验证
package Login;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;
@WebServlet(name = "ServletLogin", value = "/login")
public class ServletLogin extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=UTF-8");
PrintWriter writer = response.getWriter();
String username = request.getParameter("username");
String password = request.getParameter("password");
request.setAttribute("useranme",username);
String yan = request.getParameter("yan");
String verifyCode = String.valueOf(request.getSession().getAttribute("verifyCode"));
String s = verifyCode.toLowerCase();
if (yan.equals(s)){
QueryRunner queryRunner = new DBCon().con();
List<User> query = null;
try {
query = queryRunner.query("select * from jiaoyan", new BeanListHandler<>(User.class));
} catch (SQLException throwables) {
throwables.printStackTrace();
}
int i =3;
String pa="";
User user1 = new User();
for (User user : query) {
if (username.equals(user.getUsername()) ) {
pa = user.getPassword();
i = 0;
break;
}else{
user1=user;
i = 1;
}
}
if (i==0) {
if (password.equals(pa)){
if (request.getParameter("remember") != null) {
Cookie uCookie = new Cookie("username", user1.getUsername());
Cookie pCookie = new Cookie("password", user1.getPassword());
uCookie.setMaxAge(60 * 60 * 24 * 3);
pCookie.setMaxAge(60 * 60 * 24 * 3);
response.addCookie(uCookie);
response.addCookie(pCookie);
}
writer.write("ok");
}else {
writer.write("no");
}
} else {
writer.write("nof");
}
}else {
writer.write("yan1");
}
//String sql = "select * from jiaoyan where username='" + username + "' and password='" + password + "'";
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
后端注册
package Regist;
import Login.DBCon;
import Login.User;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;
@WebServlet(name = "ServletRegist", value = "/regist")
public class ServletRegist extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=UTF-8");
PrintWriter writer = response.getWriter();
String username = request.getParameter("username");
String password = request.getParameter("password");
String yan = request.getParameter("yan");
String verifyCode = String.valueOf(request.getSession().getAttribute("verifyCode"));
System.out.println(username);
System.out.println(password);
System.out.println(yan);
String s = verifyCode.toLowerCase();
System.out.println(s);
if (yan.equals(s)){
QueryRunner queryRunner = new DBCon().con();
List<User> query = null;
try {
query = queryRunner.query("select * from jiaoyan", new BeanListHandler<>(User.class));
} catch (SQLException throwables) {
throwables.printStackTrace();
}
boolean i = false;
for (User user : query) {
if (username.equals(user.getUsername())) {
i = true;
break;
}
}
//D:\IDEA\IdeaProjects\简单登录注册\out\artifacts\_war_exploded\img/28.jpg
if (i) {
writer.write("ccc");
// writer.write("<script>alert(\"用户名已存在!!\")</script>");
//response.sendRedirect("http://localhost:8080/_war_exploded/Regist.jsp");
} else {
int update = 0;
try {
update = queryRunner.update("insert into jiaoyan values (?,?)", username, password);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
if (update > 0) {
// writer.write("<script>alert(\"注册成功!!\")</script>");
writer.write("ok");
request.setAttribute("username",username);
// request.getRequestDispatcher("WEB-INF/T1.html").forward(request, response);
// response.sendRedirect("http://localhost:8080/_war_exploded/index.jsp");
} else {
writer.write("warn");
//writer.write("<script>alert(\"注册失败!!\")</script>");
}
}
}else {
writer.write("yan1");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
后端验证码
- 验证码工具类
package SanWa.YanZheng;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;
public class VerifyCode {
public static String drawRandomText(int width, int height, BufferedImage verifyImg) {
Graphics2D graphics = (Graphics2D) verifyImg.getGraphics();
graphics.setColor(Color.gray);//设置画笔颜色-验证码背景色
graphics.fillRect(0, 0, width, height);//填充背景
graphics.setFont(new Font("微软雅黑", Font.BOLD, 40));
//数字和字母的组合
String baseNumLetter = "123456789abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";
StringBuffer sBuffer = new StringBuffer();
int x = 10; //旋转原点的 x 坐标
String ch = "";
Random random = new Random();
for (int i = 0; i < 4; i++) {
graphics.setColor(getRandomColor());
//设置字体旋转角度
int degree = random.nextInt() % 30; //角度小于30度
int dot = random.nextInt(baseNumLetter.length());
ch = baseNumLetter.charAt(dot) + "";
sBuffer.append(ch);
//正向旋转
graphics.rotate(degree * Math.PI / 180, x, 45);
graphics.drawString(ch, x, 45);
//反向旋转
graphics.rotate(-degree * Math.PI / 180, x, 45);
x += 48;
}
//画干扰线
for (int i = 0; i < 6; i++) {
// 设置随机颜色
graphics.setColor(getRandomColor());
// 随机画线
graphics.drawLine(random.nextInt(width), random.nextInt(height),
random.nextInt(width), random.nextInt(height));
}
//添加噪点
for (int i = 0; i < 30; i++) {
int x1 = random.nextInt(width);
int y1 = random.nextInt(height);
graphics.setColor(getRandomColor());
graphics.fillRect(x1, y1, 2, 2);
}
return sBuffer.toString();
}
/**
* 随机取色
*/
private static Color getRandomColor() {
Random ran = new Random();
Color color = new Color(ran.nextInt(256),
ran.nextInt(256), ran.nextInt(256));
return color;
}
}
- 验证码生成
package SanWa.Yan;
import SanWa.YanZheng.VerifyCode;
import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
@WebServlet(name = "ServletYan", value = "/yan")
public class ServletYan extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int width = 200;
int height = 69;
BufferedImage verifyImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//生成对应宽高的初始图片
String randomText = VerifyCode.drawRandomText(width, height, verifyImg);
//单独的一个类方法,出于代码复用考虑,进行了封装。
//功能是生成验证码字符并加上噪点,干扰线,返回值为验证码字符
request.getSession().setAttribute("verifyCode", randomText);
response.setContentType("image/png");//必须设置响应内容类型为图片,否则前台不识别
OutputStream os = response.getOutputStream(); //获取文件输出流
ImageIO.write(verifyImg, "png", os);//输出图片流
os.flush();
os.close();//关闭流
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
后端跳转页面
package Login;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(name = "ServletSan", value = "/san")
public class ServletSan extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("WEB-INF/main.jsp").forward(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
前端
注册页面
<%--
Created by IntelliJ IDEA.
User: yllch
Date: 2020/10/20
Time: 16:50
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>注册</title>
<script src="js\vue.js" type="text/javascript" charset="utf-8"></script>
<script src="js\axios.min.js" type="text/javascript" charset="utf-8"></script>
<link href="#" rel="shortcut icon">
</head>
<body background="image\28.jpg">
<div id="box">
<form>
<table border="" width="700px" height="350px" align="center"
style="margin-top: 90px;background-color:lightblue;">
<tr>
<td class="xx" colspan="2" style="text-align: center;">用户注册页面</td>
<span id="warn"></span>
</tr>
<tr height="40px"
width="200px">
<td class="xx">用户名:</td>
<td class="x2">
<input type="text" name="username" v-model="username" value="" placeholder="请输入用户名6-16位字母"
@input="checkUsername()"/>
<span id="ccc"></span>
</td>
</tr>
<tr height="40px"
width="200px">
<td class="xx">密码:</td>
<td class="x2"><input type="password" name="password" v-model="password" id="psd" value=""
placeholder="请输入密码8位密码"
@input="checkPassword()"/><span
id="mima"></span></td>
</tr>
<tr height="40px"
width="200px">
<td class="xx">确认密码:</td>
<td class="x2"><input type="password" name="password1" v-model="password1" id="psd1" value=""
placeholder="请输入确认密码8位密码"
@input="checkPassword1()"/><span
id="tishi"></span></td>
</tr>
<tr height="40px"
width="200px">
<td class="xx">验证码:</td>
<td class="x2"><input type="text" name="yan" id="yan" v-model="yan" value="" placeholder="请输入验证码"
/>
<span id="yan1"></span></td>
</tr>
<tr height="60px"
width="200px">
<td class="yan">
<img id="san" src="http://localhost:8080/_war_exploded/yan" alt="" height="60px"
width="200px">
</td>
<td class="xx">
<input type="button" value="刷新" @click="change()"/>
</td>
</tr>
<tr>
<td class="xx" colspan="2" style="text-align: center;">
<input type="button" value="注册" @click="sendPost()"/>
<input type="reset" value="重置"/>
<input type="button" @click="tiao()" value="已有账号,请登录"/>
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
<script type="text/javascript">
new Vue({
el: "#box",
data: {
username: '',
password: '',
password1: '',
yan: ''
},
methods: {
sendPost() {
let param = new URLSearchParams();
param.append('username', this.username);
param.append('password', this.password);
param.append('password1', this.password1);
param.append('yan', this.yan);
axios.post('http://localhost:8080/_war_exploded/regist', param)
.then(function (response) {
if (response.data === "yan1") {
document.getElementById("yan1").innerHTML = "<font color='red'>验证码错误!</font>";
} else if (response.data === "warn") {
document.getElementById("warn").innerHTML = "<font color='red'>注册失败!</font>";
} else if (response.data === "ccc") {
document.getElementById("ccc").innerHTML = "<font color='red'>用户名已存在!</font>";
} else if (response.data === "ok") {
alert("注册成功!")
window.location = 'http://localhost:8080/_war_exploded/index.jsp';
} else {
document.getElementById("warn").innerHTML = "<font color='red'>异常错误!注册失败!</font>";
}
/* alert(response.data);document.getElementById("yan1").innerHTML ="response.data";
alert(response.status);*/
})
.catch(function (error) {
console.log(error);
});
}, change() {
document.getElementById("san").src = "http://localhost:8080/_war_exploded/yan?time=" + new Date().getTime();
}, checkUsername() {
var regx = /^[a-zA-Z]{6,16}$/;
var f = regx.test(this.username);
var cc = document.getElementById("ccc");
if (f) {
cc.innerHTML = "<font color='green'>用户名规则正确✔</font >"
} else {
cc.innerHTML = "<font color='red'>用户名格式错误</font>"
}
return f;
}, checkPassword() {
var regx1 = /^[a-zA-Z0-9]{8,16}$/;
var f1 = regx1.test(this.password);
var cc1 = document.getElementById("mima");
if (f1) {
cc1.innerHTML = "<font color='green'>密码格式正确✔</font >"
} else {
cc1.innerHTML = "<font color='red'>密码格式错误</font>"
}
return f1;
}, checkPassword1() {
var cc2 = document.getElementById("tishi");
if (this.password === this.password1) {
cc2.innerHTML = "<font color='green'>两次密码输入一致✔</font >"
} else {
cc2.innerHTML = "<font color='red'>两次密码输入不一致</font>"
}
return this.password === this.password1;
}, tiao() {
window.location = 'http://localhost:8080/_war_exploded/index.jsp';
}
}
})
</script>
登录页面
<%--
Created by IntelliJ IDEA.
User: yllch
Date: 2020/10/20
Time: 16:42
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录</title>
<script src="js\vue.js" type="text/javascript" charset="utf-8"></script>
<script src="js\axios.min.js" type="text/javascript" charset="utf-8"></script>
<link href="#" rel="shortcut icon">
</head>
<body background="image/28.jpg">
<%
Cookie[] cookies = request.getCookies();
String username="";
String password="";
if (cookies != null) {
for (Cookie cookie : cookies) {
String name = cookie.getName();
if (name.equals("username")) {
username = cookie.getValue();
}
if (name.equals("password")) {
password = cookie.getValue();
}
}
}
%>
<div id="box">
<form>
<table border="" width="700px" height="350px" align="center"
style="margin-top: 90px;background-color:lightblue;">
<tr>
<td class="xx" colspan="2" style="text-align: center;">用户登录页面</td>
<span id="warn"></span>
</tr>
<tr height="40px"
width="200px">
<td class="xx">用户名:</td>
<td class="x2">
<input type="text" name="username" v-model="username" value="<%=username%>" placeholder="请输入用户名6-16位字母"
@input="checkUsername()"/>
<span id="ccc"></span>
</td>
</tr>
<tr height="40px"
width="200px">
<td class="xx">密码:</td>
<td class="x2"><input type="password" name="password" v-model="password" id="psd" value="<%=password%>"
placeholder="请输入密码8位密码"
@input="checkPassword()"/><span
id="mima"></span><input type="checkbox" name="remember"> 记住密码
<input type="checkbox" name="remember1"> 清除密码</td>
</tr>
<tr height="40px"
width="200px">
<td class="xx">验证码:</td>
<td class="x2"><input type="text" name="yan" id="yan" v-model="yan" value="" placeholder="请输入验证码"
/>
<span id="yan1"></span></td>
</tr>
<tr height="60px"
width="200px">
<td class="yan">
<img id="san" src="http://localhost:8080/_war_exploded/yan" alt="" height="60px"
width="200px">
</td>
<td class="xx">
<input type="button" value="刷新" @click="change()"/>
</td>
</tr>
<tr>
<td class="xx" colspan="2" style="text-align: center;">
<input type="button" value="登录" @click="sendPost()"/>
<input type="reset" value="重置"/>
<input type="button" @click="tiao()" value="注册账号"/>
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
<script type="text/javascript">
new Vue({
el: "#box",
data: {
username: '',
password: '',
yan: ''
},
methods: {
sendPost() {
let param = new URLSearchParams();
param.append('username', this.username);
param.append('password', this.password);
param.append('yan', this.yan);
axios.post('http://localhost:8080/_war_exploded/login', param)
.then(function (response) {
console.log(response);
if (response.data === "yan1") {
document.getElementById("yan1").innerHTML = "<font color='red'>验证码错误!</font>";
} else if (response.data === "no") {
document.getElementById("mima").innerHTML = "<font color='red'>密码错误!</font>";
} else if (response.data === "nof") {
document.getElementById("ccc").innerHTML = "<font color='red'>用户名不存在!</font>";
} else if (response.data === "ok") {
alert("登录成功!")
window.location = 'http://localhost:8080/_war_exploded/01.jsp';
} else {
document.getElementById("warn").innerHTML = "<font color='red'>异常错误!注册失败!</font>";
}
})
.catch(function (error) {
console.log(error);
});
}, change() {
document.getElementById("san").src = "http://localhost:8080/_war_exploded/yan?time=" + new Date().getTime();
}, checkUsername() {
var regx = /^[a-zA-Z]{6,16}$/;
var f = regx.test(this.username);
var cc = document.getElementById("ccc");
if (f) {
cc.innerHTML = "<font color='green'>用户名规则正确✔</font >"
} else {
cc.innerHTML = "<font color='red'>用户名格式错误</font>"
}
return f;
}, checkPassword() {
var regx1 = /^[a-zA-Z0-9]{8,16}$/;
var f1 = regx1.test(this.password);
var cc1 = document.getElementById("mima");
if (f1) {
cc1.innerHTML = "<font color='green'>密码格式正确✔</font >"
} else {
cc1.innerHTML = "<font color='red'>密码格式错误</font>"
}
return f1;
}, tiao() {
window.location = 'http://localhost:8080/_war_exploded/ZhuCe.jsp';
}
}
})
</script>
跳转页面与登录后页面
<%--
Created by IntelliJ IDEA.
User: yllch
Date: 2020/10/23
Time: 16:34
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<jsp:forward page="/san">
<jsp:param name="username" value="sanwa"/>
</jsp:forward>
</body>
</html>
<%--
Created by IntelliJ IDEA.
User: yllch
Date: 2020/10/20
Time: 16:50
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>注册</title>
<link href="#" rel="shortcut icon">
<script src="js\vue.js" type="text/javascript" charset="utf-8"></script>
</head>
<body background="image\28.jpg">
<h1>用户 你好!</h1>
</body>
</html>