java实现网页验证码功能
程序员文章站
2024-04-01 19:00:16
本文实例为大家分享了java网页验证码的实现代码,供大家参考,具体内容如下
servlet:
package cn.bdqn.servlet;
im...
本文实例为大家分享了java网页验证码的实现代码,供大家参考,具体内容如下
servlet:
package cn.bdqn.servlet; import javax.imageio.imageio; import javax.servlet.servletexception; import javax.servlet.annotation.webservlet; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import java.awt.*; import java.awt.font.imagegraphicattribute; import java.awt.image.bufferedimage; import java.io.ioexception; import java.util.random; @webservlet(name = "servlet",urlpatterns = "/yancode") public class servlet extends httpservlet { public void dopost(javax.servlet.http.httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { this.doget(request,response); } public void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { string s="abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789"; random random = new random(); int width=500; int height=50; bufferedimage image = new bufferedimage(width,height,bufferedimage.type_int_rgb); graphics graphics = image.getgraphics();//相当于画笔 //画背景 graphics.setcolor(color.gray); graphics.fillrect(0,0,width,height); graphics.setcolor(color.black); for (int i = 0; i <4 ; i++) { int index = random.nextint(s.length()); string c = s.substring(index, index + 1); graphics.drawstring(c,width/5*(i+1),15); } imageio.write(image,"jpg",response.getoutputstream()); } }
jsp:
<%-- created by intellij idea. user: administrator date: 2017/10/10 time: 13:04 to change this template use file | settings | file templates. --%> <%@ page contenttype="text/html;charset=utf-8" language="java" %> <html> <head> <title>验证码</title> </head> <body> <img src="yancode" alt="验证码" style="width: 500px;height:50px"> <input type="button" value="看不清,更换验证码" id="btn" onclick="changecode();"> <script type="text/javascript" src="js/jquery.min.js"> </script> <script type="text/javascript" > function changecode() { $("img").attr('src', 'yancode?ts=' + new date().gettime()); } </script> </body> </html>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
下一篇: java.lang.Void类源码解析