Response验证码_分析、Response验证码_代码实现

Response验证码_分析

  创建一个对象,在内存中图片(验证码对象)

  美化图片

  将图片输出到页面展示

 

Response验证码_代码实现

 案例:

  

WebServlet( value = "/ServletZanym")
public class ServletZanym extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
this.doPost(request,response);
}


protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
int width = 100;
int heigth = 50;
// 创建一对象,在内存中图片(验证码对象)
BufferedImage image = new BufferedImage(width,heigth,BufferedImage.TYPE_INT_RGB);
// 美化验证码
Graphics graphics = image.getGraphics();//画笔对象
graphics.setColor(Color.PINK);//设置背景颜色
graphics.fillRect(0,0,width,heigth); // 填充
// 美化验证码 (画边框)
graphics.setColor(Color.blue);
graphics.drawRect(0,0,width-1,heigth-1);


// 写验证码
for (int i = 1; i <= 4; i++) {
String str="hdsjahjyuhsuetyuhihb0123456789";
// 创建一个随机的
Random random = new Random();
int index = random.nextInt(str.length());
// 获取字符
char c = str.charAt(index);
graphics.drawString(c+"",width/5*i,heigth/2);
}

// 画干扰线
graphics.setColor(Color.BLACK);
// 随机生产坐标点
for (int i = 0; i < 10; i++) {
Random r = new Random();
int x1 = r.nextInt(width);
int x2 = r.nextInt(width);
int y1 = r.nextInt(heigth);
int y2 = r.nextInt(heigth);
graphics.drawLine(x1,y1,x2,y2);
}







// 将图片输出到页面
ImageIO.write(image,"jpg",response.getOutputStream());
}
}


运行结果:

 

 

 

 

 

只要我们刷新页面,验证码就会改变

 

posted @ 2022-08-15 15:05  一位程序袁  阅读(34)  评论(0编辑  收藏  举报