创建CaptchaController
@WebServlet("/captcha")
public class CaptcheController extends HttpServlet {
private final int WIDTH = 100;
private final int HEIGHT = 60;
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
BufferedImage img = new BufferedImage(100, 80, BufferedImage.TYPE_INT_RGB);
Graphics g = img.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, WIDTH, HEIGHT);
g.setFont(new Font("宋体", 20, 20 ));
g.setColor(Color.red);
drawRandomLine(g);
String code=randomString((Graphics2D)g,4);
g.drawString(code,20,30);
g.dispose();
ServletOutputStream out = resp.getOutputStream();
ImageIO.write(img, "JPEG", out);
try {
out.flush();
} catch (Exception ex) {
} finally {
out.close();
}
}
private void drawRandomLine(Graphics g) {
g.setColor(Color.black);
for ( int i = 0 ; i < 4 ; i++ ) {
int x1 = new Random().nextInt(WIDTH);
int y1 = new Random().nextInt(HEIGHT);
int x2 = new Random().nextInt(WIDTH);
int y2 = new Random().nextInt(HEIGHT);
g.drawLine(x1, y1, x2, y2);
}
g.setColor(Color.pink);
for(int i = 0;i<100;i++){
Random ran = new Random();
int x = ran.nextInt(WIDTH);
int y = ran.nextInt(WIDTH);
g.drawOval(x,y,1,1);
}
}
public String randomString(Graphics2D g,int count) {
StringBuilder builder = new StringBuilder();
String source = "abcdefghijklmnpqrstuvwxy0123456789";
Random rnd = new Random();
for (int i = 0; i < count; i++) {
int pos = rnd.nextInt(source.length());
String s = source.substring(pos, pos + 1);
builder.append(s);
int x=5;
int degree = new Random().nextInt() % 30;
g.rotate(degree * Math.PI / 180 , x,20);
g.drawString(s, x, 20);
g.rotate(-degree * Math.PI / 180 , x,20);
x+=30;
}
return builder.toString();
}
}
测试检查随机数生成及验证码