本文实例为大家分享了javaweb servlet生成验证码的具体代码,供大家参考,具体内容如下
package com.serv; import java.awt.Color; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(urlPatterns={"/Servyzm"}) public class Servyzm extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO 自动生成的方法存根 doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO 自动生成的方法存根 Random r = new Random(); //创建图片缓冲流 BufferedImage buf = new BufferedImage(70, 25, BufferedImage.TYPE_INT_RGB); Graphics g = buf.getGraphics();//获取图片的画布对象 g.fillRect(0, 0, 70,25);//从左上角开始(0,0)坐标开始填充白色,宽70,高25 g.setColor(new Color(150,150,150));//指定的是显示的字体的颜色 String str = r.nextInt(9000)+1000+""; g.drawString(str, 20, 20);// drawString(String str, int x, int y)str指的是输出的文本;x,y指的是距离左上角的位置 for (int i = 0; i < 8; i++) { int startx = r.nextInt(120); int starty = r.nextInt(30); g.setColor(new Color(startx, 232, starty)); g.drawLine(startx, starty, startx + 10, starty + 10); } ServletOutputStream out = resp.getOutputStream();// 获取字节流 ImageIO.write(buf, "jpg", out); } // public static int getString(){ // // } }
运行截图:
更多关于验证码的文章请点击查看:《java验证码》
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自学编程网。
- 本文固定链接: https://zxbcw.cn/post/182389/
- 转载请注明:必须在正文中标注并保留原文链接
- QQ群: PHP高手阵营官方总群(344148542)
- QQ群: Yii2.0开发(304864863)