1 import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import java.awt.FontMetrics;
import javax.imageio.ImageIO; public class CreateRandomCode {
14 static String Path = "XXXXXX"; // 用户用户存放验证码的库 用户可以从库中加载验证码
15 static int RandomCount = 5; // 随机数字的位数
16 static int Width = 120; // 验证码的宽度 当校验码显示不全的时候请调整此宽度
17 static int Height = 40; // 验证码的高度
18 static int FontSize = 30; // 字体的大小 当校验码显示字体太小的时候请调整此大小 public static Color getRandColor(int fc, int bc) {// 给定范围获得随机颜色
Random random = new Random();
fc = fc > 255 ? 255 : fc;
bc = bc > 255 ? 255 : bc;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
} public static void getCode() {
BufferedImage image = new BufferedImage(Width, Height, BufferedImage.TYPE_INT_RGB); // 获取图形上下文
Graphics g = image.getGraphics(); // 生成随机类
Random random = new Random(); // 设定背景色
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, Width, Height); // 设定字体
Font font = new Font("Times New Roman", Font.PLAIN, FontSize); // 当校验码显示字体不好看的时请调整此大小 g.setFont(font);
FontMetrics fm = g.getFontMetrics(font); // System.out.println("字体大小:"+font.getSize());
// System.out.println("字体宽度:"+fm.getAscent());
// System.out.println("字体高度:"+fm.getHeight()); // 画边框
g.setColor(new Color(30, 20, 10)); // 设置边框的颜色
g.drawRect(0, 0, Width - 1, Height - 1); // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
for (int i = 0; i < 155; i++) {
g.setColor(getRandColor(160, 200)); // 设置线条的颜色
int x = random.nextInt(Width);
int y = random.nextInt(Height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x, y, x + xl, y + yl); } // 取随机产生的认证码(4位数字) RandomCount = 4 String sRand = "";
for (int i = 0; i < RandomCount; i++) {
String rand = String.valueOf(random.nextInt(10));
sRand += rand;
// 将认证码显示到图象中
g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));// 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
// 将数字画到画板上
g.drawString(rand, (int) (Width * i * 0.2 + 6), (int) (Height * 0.8)); // 参数一:字符 参数二: x坐标 参数三:y坐标
}
g.dispose(); File file = new File(Path + sRand + ".png");
OutputStream output = null;
try {
if (!file.exists()) {
file.createNewFile();
} else {
System.out.println("验证码:" + sRand + "已存在!");
}
output = new FileOutputStream(file, true); ImageIO.write(image, "png", output);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} public static void main(String[] args) {
// 随机产生一百张验证码图片 验证码库 生成一个验证码库,用户从验证码库中随机挑选一个
for (int i = 0; i < 100; i++) {
getCode();
} }
}

以上为方案一:

生成的随机验证码附图如下:

  

当需要使用验证码时,提供两种思路:

思路一:

采用OutputStream流逻辑,将验证码的文件流推送给response的流,这样Web界面上就可以显示验证码,提供参考代码如下:

image.jsp

 <%@ page contentType="image/jpeg"
import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*"%>
<%!Color getRandColor(int fc, int bc) {//给定范围获得随机颜色
Random random = new Random();
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}%>
<%
//设置页面不缓存
response.flushBuffer();
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0); // 在内存中创建图象
int width = 60, height = 20;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 获取图形上下文
Graphics g = image.getGraphics(); //生成随机类
Random random = new Random(); // 设定背景色
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, width, height); //设定字体
g.setFont(new Font("Times New Roman", Font.PLAIN, 18)); //画边框
g.setColor(new Color(30, 20, 10));
g.drawRect(0, 0, width - 1, height - 1); // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
g.setColor(getRandColor(160, 200));
for (int i = 0; i < 155; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x, y, x + xl, y + yl);
} // 取随机产生的认证码(4位数字)
String sRand = "";
for (int i = 0; i < 4; i++) {
String rand = String.valueOf(random.nextInt(10));
sRand += rand;
// 将认证码显示到图象中
g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));//调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
g.drawString(rand, 13 * i + 6, 16);
}
// 将认证码存入SESSION
session.setAttribute("rand", sRand); // 图象生效
g.dispose();
// 输出图象到页面
ServletOutputStream output = null;
try {
output = response.getOutputStream();
ImageIO.write(image, "JPEG", output); } catch (Exception e) {
e.printStackTrace();
} finally {
try {
output.flush();
output.close();
response.getOutputStream().close();
response.getOutputStream().flush(); } catch (Exception e) {
e.printStackTrace();
}
}
%>

index.jsp

 <%@page import="javax.websocket.Session"%>
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>标题</title>
<META http-equiv="Content-Type" content="text/html; charset=utf-8">
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Cache-Control" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="0">
<script>
function refreshCode() {
//alert("刷新验证码");
location.reload();
}
</script>
</head>
<body>
<form method="post" action="check.jsp">
<table>
<tr>
<td align=left>系统产生的认证码:</td>
<td> <img border=0 src="data:image.jsp">
<a href="#" onclick="refreshCode()">点击刷新</a>
</td>
</tr>
<tr>
<td align=left>输入上面的认证码:</td>
<td><input type=text name=rand maxlength=4
value="<%=request.getSession().getAttribute("rand")%>"></td>
</tr>
<%-- <tr>
<td colspan=2 align=center><input type=submit value="提交检测"></td>
<td>当前系统语言为:<%=response.getLocale()%><br> 当前地址为为:<%=request.getContextPath()%>
</td>
</tr> --%>
</table>
</form>
</body>
</html>

思路二:每次Web上从验证码库中加载验证码显示在web页面,这样做的效率比较低,但安全性较高,用户只能从已有的库中校验。

用在Web上效果如下:

java 生成随机校验码的更多相关文章

  1. java生成MD5校验码

    在Java中,java.security.MessageDigest (rt.jar中)已经定义了 MD5 的计算,所以我们只需要简单地调用即可得到 MD5 的128 位整数.然后将此 128 位计 ...

  2. 利用JAVA生成二维码

    本文章整理于慕课网的学习视频<JAVA生成二维码>,如果想看视频内容请移步慕课网. 维基百科上对于二维码的解释. 二维条码是指在一维条码的基础上扩展出另一维具有可读性的条码,使用黑白矩形图 ...

  3. java生成随机序列号

    1.java生成随机序列号 String deleteUuid = UUID.randomUUID().toString(); 引用Jar包 //java-uuid-generator-3.1.3.j ...

  4. java 生成二维码、可带LOGO、可去白边

      1.准备工作 所需jar包: JDK 1.6: commons-codec-1.11.jar core-2.2.jar javase-2.2.jar JDK 1.7: commons-codec- ...

  5. java 生成二维码后叠加LOGO并转换成base64

      1.代码 见文末推荐 2.测试 测试1:生成base64码 public static void main(String[] args) throws Exception { String dat ...

  6. java生成二维码打印到浏览器

    java生成二维码打印到浏览器   解决方法: pom.xml的依赖两个jar包: <!-- https://mvnrepository.com/artifact/com.google.zxin ...

  7. 二维码相关---java生成二维码名片,而且自己主动保存到手机通讯录中...

    版权声明:本文为博主原创文章,未经博主credreamer 同意不得转载 违者追究法律责任. https://blog.csdn.net/lidew521/article/details/244418 ...

  8. Java生成随机不反复推广码邀请码

    欢迎进入我的博客:blog.scarlettbai.com查看很多其它文章 近期接到一个需求.要批量生成推广码,首先我们知道推广码的特效有例如以下两点: 1:不可反复 2:不能够被猜測出 关于这两点, ...

  9. java生成随机字符串

    学习java comparable特性时候,定义如下Student类,需要需要随机添加学生姓名以及学号和成绩,这是java如何随机生成名字,根据我的查询,我找到目前java库支持两种方法. 1. or ...

随机推荐

  1. 【java】抽象类和接口区别

    1.语法层面上的区别 1)抽象类可以提供成员方法的实现细节,而接口中只能存在public abstract 方法: 2)抽象类中的成员变量可以是各种类型的,而接口中的成员变量只能是public sta ...

  2. 关于sql 索引

    1.聚集索引一个表只能有一个,而非聚集索引有个表能有多个 2.聚集索引和非聚集索引的根本区别是表记录的排列顺序和与索引的排列顺序是否一致,其实理解起来非常简单,还是举字典的例子:如果按照拼音查询,那么 ...

  3. 服务器对接码云webhooks

    服务安装git php代码(外网必须可以访问) <?php //本地路径滚adminasdfdasfasdf $file = "/wwwroot/webhooksLog.txt&quo ...

  4. onclick事件传递对象参数

    <a href="#"onclick="editName(JSON.stringify(data).replace(/"/g, '"'))&qu ...

  5. 多个ROS工作空间常见的问题

    1. 在/home/user_name/.bashrc文件中写入多个工作空间的环境变量,这样会导致环境变量之间相互覆盖.最常见的问题就是找不到工作空间中某个launch文件.节点.rviz插件等. 解 ...

  6. 机器学习中的train valid test以及交叉验证

    转自 https://www.cnblogs.com/rainsoul/p/6373385.html 在以前的网络训练中,有关于验证集一直比较疑惑,在一些机器学习的教程中,都会提到,将数据集分为三部分 ...

  7. [转]SQL中的case when then else end用法

      Case具有两种格式.简单Case函数和Case搜索函数. --简单Case函数 CASE sex WHEN '1' THEN '男' WHEN '2' THEN '女' ELSE '其他' EN ...

  8. WPF 和 百度 eChart 交互

    https://blog.csdn.net/defrt4/article/details/52689052

  9. 用户层APC队列使用

    一 参考 https://docs.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-que ...

  10. Windows下通过pip安装PyTorch 0.4.0 import报错

    问题:通过pip安装PyTorch 0.4.0成功,但是import时报错. import torch  File "D:\Python\Python36\lib\site-packages ...