随机产生验证码的工具类:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class ImageUtil {
//高度
private static int width = 80;
//宽度
private static int height = 30;
//随机对象
private static Random rd = new Random();
public static BufferedImage createImage() {
//创建图片对象
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
//设置背景颜色
g.setColor(Color.GRAY);
g.fillRect(0, 0, width, height);
//设置字体颜色
g.setColor(Color.black);
String temp = "\u7684\u4e00\u4e86\u662f\u6211\u4e0d\u5728\u4eba\u4eec\u6709\u6765\u4ed6\u8fd9\u4e0a\u7740\u4e2a\u5730\u5230\u5927\u91cc\u8bf4\u5c31\u53bb\u5b50\u5f97\u4e5f\u548c\u90a3\u8981\u4e0b\u770b\u5929\u65f6\u8fc7\u51fa\u5c0f\u4e48";
int len = temp.length();
//随机选取不重复的四个汉字
Set<String> set = new HashSet<String>();
while (set.size() < 4) {
int index = rd.nextInt(len);
set.add(String.valueOf(temp.charAt(index)));
}
StringBuffer sb = new StringBuffer();
for (String s : set) {
sb.append(s);
}
g.drawString(sb.toString(), 15, 18);
g.setColor(Color.orange);
// 随机产生4条直线(干扰线)
for (int i = 0; i < 4; i++) {
int x1 = rd.nextInt(80);
int y1 = rd.nextInt(30);
int x2 = rd.nextInt(80);
int y2 = rd.nextInt(30);
g.drawLine(x1, y1, x2, y2);
}
return image;
}
}
servlet控制端验证:
public class CheckCodeServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/*
* tomcat 的conf/web.xml文件中
* <extension>jpeg</extension>
* <mime-type>image/jpeg</mime-type>
*/
//设置相应类型
response.setContentType("image/jpeg");
//打给浏览器
ImageIO.write(ImageUtil.createImage(), "jpeg",
response.getOutputStream());
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}