本文小编为大家详细介绍“小程序如何实现简单的生成随机验证码”,内容详细,步骤清晰,细节处理妥当,希望这篇“小程序如何实现简单的生成随机验证码”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。
//随机生成验证码
//第一步:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
test(response);
}
private void test(HttpServletResponse response) throws IOException {
int width = 120,height=25;
//生成一张图片 此时得到一张宽120,长25的一张黑色图片
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics grap = img.getGraphics();//得到一个画笔
//填充背景色
grap.setColor(Color.pink);
//设置填充的区域
grap.fillRect(1, 1, width-2, height-2);
//设置边框的颜色 同填充背景颜色 靠近谁是设置哪个属性的颜色
grap.setColor(Color.red);
grap.drawRect(0, 0, width-1, height-1);
//设置字体
grap.setFont(new Font("黑体", Font.BOLD|Font.ITALIC, 18));
//向图片上写字 嘿嘿随机生成了字符串
Random r = new Random();
int p = 15;
for(int i=1;i<=4;i++)
{
grap.drawString(r.nextInt(10)+"", p,20);
p+=15;
}
//向图片上画线
for(int i=1;i<=10;i++)
{
grap.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
}
//把图片发送给客户端
ImageIO.write(img, "jpg", response.getOutputStream());
}
//第二部:新建login.html
<!DOCTYPE html>
<html>
<head><title>login.html</title>
<script type="text/javascript">
function ff(){
var img = document.getElementById("image");
img.src="/day33_response/demo4?user=1"+new Date().getTime();
// img.setAttribute("src","/day33_response/demo4?user="+new Date().getTime());
}
</script>
</head>
<body> <form action="#" method="get"> 用户名<input type="text" name="uname"><br/><br/> 密 码<input type="password" name="pwd"><br/><br/> 验证码<input type="text" name="code"> <!-- 如果image没有写src页面刚加载时没有东西,刷新之后才会显示验证码图片 --> <img id="image" src='/day33_response/demo4'> <!-- 换两行 --> <a href="javascript:ff()">换一张</a><br/> <br/>
<input type="submit" value="提交">
</form>
</body>
</html>
// 大功告成就可以发布到tomcat上浏览了
//此处介绍一种懒人方法,在doGet方法中,其中ValidateCode四个函数分别是矩形的宽、高以及验证码的个数和干扰线的条数,然后第一步的函数就可统统省略了
ValidateCode code = new ValidateCode(320, 25, 4, 8);
code.write(response.getOutputStream());
//注:导相应的ValidateCode的JAR包喔。
读到这里,这篇“小程序如何实现简单的生成随机验证码”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。