使用Java如何生成验证码.docxVIP

  • 2
  • 0
  • 约1.76千字
  • 约 3页
  • 2017-02-05 发布于河南
  • 举报
使用Java如何生成验证码

Java生成大小写字母数字混合验证码作者:小孩丛丛代码如下:package gucong.response;import java.awt.Color;import java.awt.Font;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.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class AuthCodeDemo extends HttpServlet {//定义一个方法可以获取到a-z或A-Z或0-9的ASCII码值的随机数public int ro() {int b = 0;Random r = new Random();while (true) {int a = (int) (r.nextDouble() * 123);if ((a = a a = z) || (a = A a = Z)|| (a 47 a 58)) {b = a;break;}}return b;}public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//定义大小的值int width=120,height=25;//在内存产生一个图片BufferedImage bimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);//得到画笔Graphics g =bimage.getGraphics();//画一个矩形g.setColor(Color.BLUE);g.drawRect(0, 0, width, height);//画填充背景g.setColor(Color.RED);g.fillRect(1, 1, width-2, height-2);//画干扰线条 20条g.setColor(Color.GRAY);Random r = new Random();for (int i = 0; i 20; i++) {g.drawLine(r.nextInt(width),r.nextInt(height),r.nextInt(width),r.nextInt(height));}//画随机数字g.setColor(Color.YELLOW);g.setFont(new Font(黑体,Font.BOLD|Font.ITALIC,20));//生成4个随机数字for (int i = 0; i 4; i++) {//这里调用的是上面的ro()方法,并进行的了强制转换,转换成charchar a = (char)ro();//此方法中只能是字符串 , 数字, 数字类型。g.drawString(a+,20*i, 20);}//输出图像到页面response.setContentType(image/jpeg);ImageIO.write(bimage, jpg, response.getOutputStream());}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {this.doGet(request, response);}}访问这个页面

文档评论(0)

1亿VIP精品文档

相关文档