很简陋的验证码学习

大体三步

1.创建验证码图片对象
BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//2.美化图片  。。。。。
//3.把验证码图片输出到页面展示
ImageIO.write(image,"jpg",response.getOutputStream());
其对应的Servlet类为:
@WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int width=100;
int height=50;
//1.创建验证码图片对象
BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);

//2.美化图片
Graphics g = image.getGraphics();
g.setColor(Color.pink);
g.fillRect(0,0,width,height);

g.setColor(Color.BLUE);
g.drawRect(0,0,width-1,height-1);

String str="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnoprstuvwxyz0123456789";
Random random=new Random();

for (int i=1;i<=4;i++){
int index = random.nextInt(str.length());
g.drawString(str.charAt(index)+"",i*width/5,height/2);
}


//画干扰线 5条
g.setColor(Color.GREEN);
for (int i = 0; i < 10; i++) {
int x1 = random.nextInt(width);
int x2 = random.nextInt(width);
int y1 = random.nextInt(height);
int y2 = random.nextInt(height);
g.drawLine(x1,y1,x2,y2);
}

//3.把验证码图片输出到页面展示
ImageIO.write(image,"jpg",response.getOutputStream());
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
HTML页面




点击切换验证码






看不清?换一张

 

你可能感兴趣的:(很简陋的验证码学习)