随机产生验证码的工具类:
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 = "u7684u4e00u4e86u662fu6211u4e0du5728u4ebau4eecu6709u6765u4ed6u8fd9u4e0au7740u4e2au5730u5230u5927u91ccu8bf4u5c31u53bbu5b50u5f97u4e5fu548cu90a3u8981u4e0bu770bu5929u65f6u8fc7u51fau5c0fu4e48";
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);
}
}