演示
演示代码字节流
定义图片对象
设置画笔
x y 设置位置
画边框
注意 右 和 下 没有边框 ,原因是矩形打了,变小一点就可以了
写文字
验证码随机
随机干扰线
让图片在指定的位置显示
点击换图
让文字变大
实战
这个是验证码的servlet
package servlet;
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 javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
@WebServlet("/verifyCode")
public class VerifyCode extends HttpServlet {
private Random random = new Random();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取字节输出流的对象
ServletOutputStream outputStream = resp.getOutputStream();
//获得一个图片对象
int width = 100;
int height = 50;
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//图片背景
Graphics graphics = bufferedImage.getGraphics();
graphics.setColor(Color.BLUE);
graphics.fillRect(0, 0, width, height);
// 验证码内边框
graphics.setColor(Color.RED);
graphics.drawRect(0, 0, width - 1, height - 1);
// 获取验证码内容
String code = getCode();
// 存到 session
HttpSession session = req.getSession();
session.setAttribute("code",code);
// 文字变大了,y 坐标就要变
int y = 30;
graphics.setColor(Color.YELLOW);
// 让文字变大
graphics.setFont(new Font("simhei", Font.PLAIN, 24));
for (int i = 0; i < code.length(); i++) {
String c = code.charAt(i) + "";
int n = i + 1;
int x = n * 20;
graphics.drawString(c, x, y);
}
// 干扰线
graphics.setColor(Color.RED);
for (int i = 0; i < 20; i++) {
//生成坐标
// 横坐标
int x1 = random.nextInt(width);
int x2 = random.nextInt(width);
// 纵坐标
int y1 = random.nextInt(height);
int y2 = random.nextInt(height);
//画线
graphics.drawLine(x1, y1, x2, y2);
}
// 返回给游览器
ImageIO.write(bufferedImage, "jpg", outputStream);
}
private String getCode() {
// 内容池
String content = "abcdABCDEFG123456789";
String code = "";
for (int i = 0; i < 4; i++) {
int idx = random.nextInt(content.length());
char c = content.charAt(idx);
code += c;
}
return code;
}
}
下面是页面
<%--
Created by IntelliJ IDEA.
User: SSOA
Date: 2022/6/9
Time: 13:48
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/css/style.css"/>
<!--[if IE 6]>
<script src="${pageContext.request.contextPath}/js/iepng.js" type="text/javascript"></script>
<script type="text/javascript">
EvPNG.fix('div, ul, img, li, input, a');
</script>
<![endif]-->
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.11.1.min_044d0927.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.bxslider_e88acd1b.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/menu.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/select.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/lrscroll.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/iban.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/fban.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/f_ban.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/mban.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/bban.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/hban.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/tban.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/lrscroll_1.js"></script>
<script src="${pageContext.request.contextPath}/js/jquery-1.8.2.min.js"></script>
<script>
// 验证码是否OK
var myCode_is_ok = false;
function form_submit() {
// 定义一个开关
var isOk = true;
$("input:text").each(function (idx, item) {
var len = $(item).val().trim().length;
if (len === 0) {
isOk = false;
return false;
}
})
// 判断开关
if (!isOk) {
alert("数据不完整请重新再试")
return false;
}
// 返回结果
return myCode_is_ok;
}
// 换一张图片
function change_code() {
// 获取时间戳
let s = Date().valueOf();
// 本质就是重新找服务器要一个新的验证码的图片
$("img.code_img").prop("src", "${pageContext.request.contextPath}/verifyCode?a=" + s)
}
function check_my_code() {
alert(111)
// 验证码是否正确
// 发 ajax 请求
let userCode = $("input.l_ipt").val();
var myData = {"userCode": userCode};
$.ajax({
url: "checkCode",
data: myData,
dataType: "json",
type: "get",
success: function (result) {
console.log(result);
console.log(result["isOK"])
// 把消息给内容区
if (result["isOK"] === "0") {
// {"isOk":"0","msg":"验证码有误"}
$("span.code_msg").text(result["msg"]);
myCode_is_ok = false;
} else {
// {"isOk":"1","msg":"验证通过"}
$("span.code_msg").text("");
myCode_is_ok = true;
}
console.log(myCode_is_ok)
}
})
}
$(function () {
change_code();
// 非空验证
$("form").submit(form_submit);
// 给 a 连接添加点击事件
$("a.change_code").click(change_code);
// 当验证码的按钮失去焦点的时候
$("input.l_ipt").change(check_my_code);
})
</script>
<title>尤洪</title>
</head>
<body>
<!--Begin Header Begin-->
<div class="soubg">
<div class="sou">
<span class="fr">
<span class="fl">你好,请<a href="Login.html">登录</a> <a href="Regist.html" style="color:#ff4e00;">免费注册</a>
<a href="Regist.html" style="color:#ff4e00;">验证码登录</a> <a href="Regist.html" style="color:#ff4e00;">微信登录</a>
|<a href="#">我的订单</a> |<a href="#">后台管理</a> |<a href="#">注销
</span>
</div>
</div>
<!--End Header End-->
<!--Begin Login Begin-->
<div class="log_bg">
<div class="top">
<div class="logo"><a href="Index.html"><img src="${pageContext.request.contextPath}/images/logo.png"/></a></div>
</div>
<div class="regist">
<div class="log_img"><img src="${pageContext.request.contextPath}/images/l_img.png" width="611" height="425"/>
</div>
<div class="reg_c">
<form action="user" method="post">
<input type="hidden" name="action" value="regist">
<table border="0" style="width:420px; font-size:14px; margin-top:20px;" cellspacing="0" cellpadding="0">
<tr height="50" valign="top">
<td width="95"> </td>
<td>
<span class="fl" style="font-size:24px;">注册</span>
<span class="fr">已有商城账号,<a href="Login.html" style="color:#ff4e00;">我要登录</a></span>
</td>
</tr>
<tr height="50">
<td align="right"><font color="#ff4e00">*</font> 用户名 </td>
<td><input type="text" name="loginName" value="" class="l_user"/></td>
</tr>
<tr height="50">
<td align="right"><font color="#ff4e00">*</font> 密码 </td>
<td><input type="password" name="password1" value="" class="l_pwd"/></td>
</tr>
<tr height="50">
<td align="right"><font color="#ff4e00">*</font> 确认密码 </td>
<td><input type="password" name="password2" value="" class="l_pwd"/></td>
</tr>
<tr height="50">
<td align="right"><font color="#ff4e00">*</font> 邮箱 </td>
<td><input type="text" name="email" value="" class="l_email"/></td>
</tr>
<tr height="50">
<td align="right"><font color="#ff4e00">*</font> 手机 </td>
<td><input type="text" name="mobile" value="" class="l_tel"/></td>
</tr>
<tr height="50">
<td align="right">昵称 </td>
<td><input type="text" name="userName" value="" class="l_mem"/></td>
</tr>
<tr height="50">
<td align="right">性别 </td>
<td>
<input type="radio" name="sex" value="1" checked>男
<input type="radio" name="sex" value="0">女
</td>
</tr>
<tr height="50">
<td align="right"><font color="#ff4e00">*</font> 验证码 </td>
<td>
<input type="text" value="" class="l_ipt"/>
<img class="code_img" src="${pageContext.request.contextPath}/verifyCode" alt="验证码">
<a class="change_code" href="javascript:;" style="font-size:12px; font-family:'宋体';">换一张</a>
<span class="code_msg" style="color: red"></span>
</td>
</tr>
<tr>
<td> </td>
<td style="font-size:12px; padding-top:20px;">
<span style="font-family:'宋体';" class="fl">
<label class="r_rad"><input type="checkbox"/></label><label class="r_txt">我已阅读并接受《用户协议》</label>
</span>
</td>
</tr>
<tr height="60">
<td> </td>
<td><input type="submit" value="立即注册" class="log_btn"/></td>
</tr>
</table>
</form>
</div>
</div>
</div>
<!--End Login End-->
<!--Begin Footer Begin-->
<div class="btmbg">
<div class="btm">
备案/许可证编号:蜀ICP备12009302号-1-www.dingguagua.com Copyright © 2015-2018 尤洪商城网 All Rights Reserved. 复制必究 , Technical
Support: Dgg Group <br/>
<img src="${pageContext.request.contextPath}/images/b_1.gif" width="98" height="33"/><img
src="${pageContext.request.contextPath}/images/b_2.gif" width="98" height="33"/><img
src="${pageContext.request.contextPath}/images/b_3.gif" width="98" height="33"/><img
src="${pageContext.request.contextPath}/images/b_4.gif" width="98" height="33"/><img
src="${pageContext.request.contextPath}/images/b_5.gif" width="98" height="33"/><img
src="${pageContext.request.contextPath}/images/b_6.gif" width="98" height="33"/>
</div>
</div>
<!--End Footer End -->
</body>
<!--[if IE 6]>
<script src="//letskillie6.googlecode.com/svn/trunk/2/zh_CN.js"></script>
<![endif]-->
</html>