使用技术:
JSP + Ajax
随机生成验证码,动态验证。
功能:随机生成验证码,存入会话,生成验证码图片,供输入验证,
若验证成功,提示:验证码输入成功,并且将注册按钮启用;
若验证失败,提示:验证码输入错误,并且将注册按钮禁用,并且在会话中删除缓存的验证码数据。
若会话中没有存储验证码数据,则提醒:验证码已失效,点击刷新。
验证码点击可以刷新
1、验证码输入成功
image.png
2、验证码输入失败
image.png
验证码输入失败
3、验证码失效
image.png
验证码失效
代码:
1、 随机生成验证码代码,VerificationCodeServlet.java:
package com.company.project.servlet;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sun.prism.Image;
@WebServlet("/verification-code-servlet")
public class VerificationCodeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
//设置生成验证码的画布宽度
int w = 80;
//生成验证码的长度
int fontNum = 4;
//验证码字体大小
int fontSize = (w - 10) / fontNum;
//根据字体大小设置画布的高度
int h = (int) (fontSize * 1.5);
//初始化字符源
String charSource = "abcdefghijklmnopqrstuvwxyxABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
/**
* 随机生成验证码
* @param num 生成验证码的长度
* @return 验证码
*/
public String randString(int num) {
String verCode = "";
for(int i = 0;i<num;i++) {
verCode += charSource.charAt((int)(Math.random()*charSource.length()));
}
System.out.println("verCode:"+verCode);
return verCode;
}
public Color randColor() {
int r = (int)(Math.random() * 256);
int g = (int)(Math.random() * 256);
int b = (int)(Math.random() * 256);
Color color = new Color(r, g, b);
System.out.println("color:"+color);
return color;
}
/**
* 随机生成一条直线
* @return 两点坐标(x1,y1)(x2,y2)
*/
public int[] randLine() {
int x1,x2,y1,y2;
x1 = (int)(Math.random()*w);
x2 = (int)(Math.random()*w);
y1 = (int)(Math.random()*h);
y2 = (int)(Math.random()*h);
int[] result = {x1,y1,x2,y2};
return result;
}
public VerificationCodeServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//初始化画布
BufferedImage canvas = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
//初始化画笔对象
Graphics pen = canvas.getGraphics();
//设置画笔颜色
pen.setColor(Color.WHITE);
//画一个填充矩形
pen.fillRect(0, 0, w, h);
//设置画笔颜色
pen.setColor(Color.black);
//画出边框
pen.drawRect(0, 0, w-1, h-1);
//设置画笔字体样式
pen.setFont(new Font("微软雅黑", Font.BOLD, fontSize));
//生成验证码字符串
String verCode = randString(fontNum);
//将生成的验证码存入会话
request.getSession().setAttribute("verCode", verCode);
//绘制随机验证码
for(int i = 0;i<verCode.length();i++) {
pen.setColor(randColor());
pen.drawString(String.valueOf(verCode.charAt(i)), 10 + i * 15, (h + fontSize) /2);
}
//绘制一条随机直线
int[] line = randLine();
for(int i = 0;i<line.length;i++) {
System.out.println(line[i]);
}
//设置画笔字体样式
pen.setColor(Color.BLACK);
//画出随机直线
pen.drawLine(line[0],line[1],line[2],line[3]);
//获取输出流对象
ServletOutputStream out = response.getOutputStream();
//把画好的验证码写入输出流
ImageIO.write(canvas, "png", out);
//释放输出流
out.flush();
out.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
2、验证码认证,VerifyServlet.java
package com.company.project.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/verify-servlet")
public class VerifyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public VerifyServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");
request.setCharacterEncoding("utf-8");
String verCode = request.getParameter("verCode");
System.out.println("-----------------");
String flag = null ;
String code = (String) request.getSession().getAttribute("verCode");
if(code==null) {
//验证码失效
flag = "0";
}
else if(verCode.toUpperCase().equals(code.toUpperCase())) {
//验证码输入正确
flag = "1";
}else {
//验证码输入失败
flag = "2";
request.getSession().removeAttribute("verCode");
}
PrintWriter out=response.getWriter();
out.print(flag);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
3、验证码页面,verCode.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录</title>
<script>
var baseUrl = "http://localhost:8888/JavaEE17Demo/verify-servlet";
var xmlHttp;
var responseText;
var onBlurId;
var code;
//创建创建 XMLHttp 对象
function createXmlHttp(name, value) {
if(window.ActiveXObject) {
console.log("操作提示:您的浏览器是IE浏览器。");
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else if(window.XMLHttpRequest) {
console.log("操作提示:您的浏览器不是IE浏览器。");
xmlHttp = new XMLHttpRequest();
}
//注册监听或者回调函数
xmlHttp.onreadystatechange = callback;
//1:打开状态
//传递参数
var url = baseUrl + "?" + name + "=" + value;
//GET方法打开,第三个参数如果为true,那么为异步请求,将不会刷新整个页面.
xmlHttp.open("GET", url, true);
//2:发送状态
//Get方式的send()
xmlHttp.send(null);
}
//回调函数,处理响应信息
function callback() {
//获取响应内容
if(xmlHttp.readyState == 4) {
if(xmlHttp.status == 200) {
responseText = xmlHttp.responseText;
console.log(responseText);
var pText = document.getElementById("pText");
var button = document.getElementById("regButton");
if(responseText == "0") {
pText.style.color = "red";
button.disabled = true;
pText.innerHTML="验证码已失效,点击刷新";
} else if(responseText == "1") {
pText.style.color = "green";
button.disabled = false;
pText.innerHTML="验证码输入成功";
}else{
pText.style.color = "red";
button.disabled = true;
pText.innerHTML="验证码输入失败";
}
}
}
}
//通过处理后的响应信息修改提醒文本
function setResponseText(text) {
var id;
var responseText;
}
//重写失去焦点事件
function onBlur(id) {
var module = document.getElementById(id);
var name = module.name;
var value = module.value;
//var url = baseUrl + "?" + name + "=" + value;
onBlurId = id;
console.log(name + "失去焦点");
console.log(name + ":" + value);
createXmlHttp(name, value);
}
function onClick(){
var id = Math.floor(Math.random()*10);
code = document.getElementById("verCodeImg");
console.log(code);
code.src = "http://localhost:8888/JavaEE17Demo/verification-code-servlet"+"?id="+id;
console.log(code.src);
}
</script>
</head>
<body>
<form id="Login" action="" method="post">
<table>
<tr>
<td>邮箱: <input name="e-mail" id="e-mail" type="text" /></td>
<td>
<p id="pText1" style="color: red;"></p>
</td>
</tr>
<tr>
<td>手机号: <input name="phoneNum" type="text" id="phoneNum" /></td>
<td>
<p id="pText2" style="color: red;"></p>
</td>
</tr>
<tr>
<td>验证码: <input type="text" id="verCode" name="verCode" onblur="onBlur(id)"/></td>
<td><img id="verCodeImg" alt="随机生成验证码" src="http://localhost:8888/JavaEE17Demo/verification-code-servlet" onclick="onClick()" ></td>
<td>
<p id="pText" style="color: red;"></p>
</td>
</tr>
</table>
<input type="button" id="regButton" value="注册" disabled="true"/>
</form>
</body>
</html>