博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JSP生成验证码
阅读量:7043 次
发布时间:2019-06-28

本文共 1900 字,大约阅读时间需要 6 分钟。

在浏览网页时,我们会经常看到验证码,尤其是登录和注册的时候,今天就为大家介绍一下如何使用JSP生成验证码图片,原理其实是很简单的,直接上代码:

<%@ page contentType="image/jpeg;charset=utf-8" pageEncoding="GBK" %><%@    page import="java.util.*,java.awt.*,java.awt.image.*,javax.imageio.*"         import="java.io.OutputStream" %><%!   Color getRandColor(int fc,int bc)   {      Random rd = new Random();      if (fc > 255) fc = 255;      if (bc > 255) bc = 255;      int red = fc + rd.nextInt(bc - fc);      int green = fc + rd.nextInt(bc - fc);      int blue = fc + rd.nextInt(bc - fc);      return new Color(red, green, blue);   }%>   <%   Random r = new Random();   response.addHeader("Pragma", "No-cache");   response.addHeader("Cache-Control", "no-cache");   response.addDateHeader("expires", 0);   int width = 80;   int height = 32;   BufferedImage pic = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);   Graphics gc = pic.getGraphics();   gc.setColor(getRandColor(200, 250));   gc.fillRect(0, 0, width, height);   String[] rNum = {
"1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "W", "X", "Y", "Z"}; int[] style = {Font.PLAIN, Font.BOLD, Font.ITALIC, Font.PLAIN + Font.BOLD, Font.BOLD + Font.ITALIC, Font.PLAIN + Font.ITALIC, Font.PLAIN + Font.BOLD + Font.ITALIC}; gc.setColor(getRandColor(60,150)); String rt = ""; for(int i = 0; i < 4; i++) { String temp = rNum[r.nextInt(rNum.length)]; rt = rt + temp; gc.setFont(new Font("Times New Roman", style[r.nextInt(7)], 21)); gc.drawString(temp, 15 + 13 * i + r.nextInt(2), 23); } gc.dispose(); OutputStream os = response.getOutputStream(); ImageIO.write(pic, "JPEG", os); os.flush(); os.close(); os = null; response.flushBuffer(); out.clear(); out = pageContext.pushBody();%>

运行程序,通过浏览器访问,我们会看到浏览器上显示

这里写图片描述

大家可以自己尝试在绘图的时候增加一些删除线之类的,提高验证码识别难度。

你可能感兴趣的文章
CentOS下bond的配置方法
查看>>
使用redis作为mybatis的二级缓存
查看>>
认识Android MVP
查看>>
端口镜像 SPAN && RSPAN
查看>>
跨界的一点点感悟
查看>>
在有母版页的页面里使用FindControl的困惑
查看>>
UI设计师面试时必须注意的6大问题
查看>>
无线宽带路由器300M导致的网络故障
查看>>
VMware Virtual SAN 设计与规模调整指南
查看>>
我的友情链接
查看>>
SET-MAP现代诗一首
查看>>
ConfigParser
查看>>
CentOS系统启动
查看>>
浅尝 Windows Server 2016 —— Container 容器:概念
查看>>
我的友情链接
查看>>
MSBuild
查看>>
6.3 bash编程 字符测试
查看>>
配置管理小报091124:*** glibc detected *** double free or corruption (fasttop): 0x08b60068 ***
查看>>
配置管理小报101010:数据库修复方法。
查看>>
Linux安装配置apache
查看>>