本文是一个很简单的向网页上输出验证码的实现喲!通过注释解释清楚了每一步!
Myeclipse下的Package Explorer显示文件结构如下:
ResponseDemo.java实现了输出随机图片的功能:
1 package com.yyz.response; 2 3 import java.awt.Color; 4 import java.awt.Font; 5 import java.awt.Graphics; 6 import java.awt.image.BufferedImage; 7 import java.io.IOException; 8 import java.util.Random; 9 10 import javax.imageio.ImageIO; 11 import javax.servlet.ServletException; 12 import javax.servlet.http.HttpServlet; 13 import javax.servlet.http.HttpServletRequest; 14 import javax.servlet.http.HttpServletResponse; 15 //输出随机图片 16 public class ResponseDemo extends HttpServlet { 17 18 public void doGet(HttpServletRequest request, HttpServletResponse response) 19 throws ServletException, IOException { 20 //6.设置头,控制浏览器不要缓存图片数据 21 response.setHeader("Expires", "-1"); 22 response.setHeader("Cache-Control", "no-cache"); 23 response.setHeader("Pragma", "no-cache"); 24 25 //5.通知浏览器以图片方式打开 26 response.setHeader("Content-type", "image/jpeg"); 27 //1.在内存中创建一副图片 28 BufferedImage image = new BufferedImage(80,20,BufferedImage.TYPE_INT_RGB); 29 //2.得到图片 30 Graphics g = image.getGraphics(); 31 //修改图片背景色 32 g.setColor(Color.WHITE); 33 g.fillRect(0, 0,80, 20); 34 //3.向图片上写数据 35 g.setColor(Color.BLUE); 36 g.setFont(new Font(null,Font.BOLD,20)); 37 g.drawString(nakeNum(), 0, 20); 38 //随机画出9条干扰线 39 Random rand = new Random(); 40 for(int i = 0;i<9;i++){ 41 g.setColor(Color.BLACK); 42 int x1 = rand.nextInt(80); 43 int y1 = rand.nextInt(20); 44 int x2 = rand.nextInt(80); 45 int y2 = rand.nextInt(20); 46 g.drawLine(x1, y1, x2, y2); 47 } 48 //4.将图片写给浏览器 49 ImageIO.write(image, "jpeg", response.getOutputStream()); 50 51 } 52 53 private String nakeNum() { 54 Random r = new Random(); 55 String num = r.nextInt(9999999)+"";//产生0-9999999的数字,但有可能不足7位,如123 56 StringBuffer sb = new StringBuffer(); 57 for(int i = 0;i<7-num.length();i++){ 58 sb.append("0"); 59 } 60 return sb.toString()+num; 61 } 62 63 public void doPost(HttpServletRequest request, HttpServletResponse response) 64 throws ServletException, IOException { 65 doGet(request,response); 66 } 67 }
register.html是一个简单的注册页面,通过img标签执行ResponseDemo.java:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>register.html</title> 5 <meta name="keywords" content="keyword1,keyword2,keyword3"> 6 <meta name="description" content="this is my page"> 7 <meta name="content-type" content="text/html; charset=UTF-8"> 8 </head> 9 <body> 10 <form action=""> 11 用户名:<input type="text" name="username"> 12 密码:<input type="password" name="password"> 13 认证码:<input type="text" name="checkcode"><img src="/day06/servlet/ResponseDemo"> 14 <input type="submit " value="注册"> <br> 15 <br> 16 </body> 17 </html>
最后附上测试结果:
输出随机图片时,图片上若想要输出中文,可以用一个字符数组存储多个汉字(直接存汉字的编码也行),然后用Random产生的随机数做下标取出对应中文,再产生要写上图片的字符串即可。
时间: 2024-10-06 22:27:09