失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > 生成登录验证码 点击更换验证码图片

生成登录验证码 点击更换验证码图片

时间:2020-05-20 07:13:02

相关推荐

生成登录验证码 点击更换验证码图片

验证码最终效果:

直接上代码:

1、 service层代码

/** 生成验证码 并将验证码转化为图片的业务* */public class VerificationCodeService {public VerificationCodeService() {}// 生成验证码字符串 -- 随机数public String createRandomCode() {String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";//所有随机数字符串集合//Random类 产生指定范围内的随机数Random random = new Random();StringBuilder sb = new StringBuilder();//随机截取4个字符for(int i =0 ;i < 4; i++){//4个随机数//包括开头不包括结尾 从0到str.length()-1里面随机产生一个整数int index = random.nextInt(str.length());//从0到str.length()不包括最后一个 右边开区间char randomStr = str.charAt(index);//安装随机产生的值获取字符sb.append(randomStr);//StringBuilder拼接字符串}return sb.toString();}// 将生成的随机字符串验证码转化为图片public BufferedImage changeStringToImage(String code) {Random rd = new Random();//创建一个画布BufferedImage image = new BufferedImage(75, 28, BufferedImage.TYPE_INT_RGB);//创建画笔Graphics g = image.getGraphics();//给画笔设置颜色(绘制随机验证码的时候的验证码颜色)g.setColor(new Color(240,240,240)); //#00000 FFFFFF//设置验证码的 背景色g.fillRect(0, 0, 75, 28);// 设置字体g.setFont(new Font("宋体",Font.BOLD,16));g.setColor(new Color(0,0,0)); //#00000 FFFFFF// g.drawString(checkCodeStr, 20, 20);for (int i = 0; i <4 ; i++) {//画字符g.setColor(new Color(rd.nextInt(120),rd.nextInt(120),rd.nextInt(120)));g.drawString(code.charAt(i)+"", 16*i + rd.nextInt(16), 15 + rd.nextInt(10) );if(i % 2 == 0) {//画线g.setColor(new Color(rd.nextInt(120), rd.nextInt(120), rd.nextInt(120)));g.drawLine(rd.nextInt(75), rd.nextInt(28), rd.nextInt(75), rd.nextInt(28));}}return image;}}

2、servlet层

/* 生成验证码显示成图片的servlet */@WebServlet("/ImageCodeSevlet")public class ImageCodeSevlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//1:创建一个验证码的业务VerificationCodeService vcs = new VerificationCodeService();//2:生产一个随机的4个字符组成的字符串String code = vcs.createRandomCode();System.out.println(code);//3:将字符串转成图片//BufferedImage类将图片生成到内存中,然后直接发送给浏览器BufferedImage image = vcs.changeStringToImage(code);//4:使用OutputStream写到浏览器System.out.println(image);ImageIO.write(image,"jpeg",response.getOutputStream());//参1,内存中的图片 参2,格式 参3,字节输出流}}

3、界面

<html><head><title>登录</title></head><body><form action="/Login/login" method="post"><table><td>请输入验证码:<input type="text" id="imagecode" width="20px"/><td><img id="image" src="ImageCodeSevlet" alt="点击刷新验证码"></td></tr></table><input type="submit" value="登录"></form><script type="application/javascript">var image = document.getElementById("image");/* 点击图片刷新验证码 */image.onclick = function(){image.src = "ImageCodeSevlet?time="+new Date();//加一个时间戳}</script></body></html>

如果觉得《生成登录验证码 点击更换验证码图片》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。