jsp中response设置验证码

public static final int WIDTH=125;
public static final int HEIGHT=35;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
BufferedImage image=new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);

Graphics g=image.getGraphics();
 
setBackGround(g);//1.设置背景

setBorder(g);  //2.设置边框

drawRandomLine(g);//3.设置随机线

drawRandomNum((Graphics2D)g);//4.设置随机数
response.setContentType("image/jpeg");
ImageIO.write(image, "jpg", response.getOutputStream()); //5。设置浏览器的显示
}
private void setBackGround(Graphics g) {
g.setColor(Color.white);
g.fillRect(0, 0, WIDTH, HEIGHT);
}
private void setBorder(Graphics g) {
g.setColor(Color.BLACK);
g.fillRect(1, 1, WIDTH-2, HEIGHT-2);

}
private void drawRandomLine(Graphics g) {
g.setColor(Color.GREEN);
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);
}
}
private void drawRandomNum(Graphics2D g) {
g.setColor(Color.red);
g.setFont(new Font("宋体",Font.BOLD,20));
int x=10;
for(int i=0;i<4;i++){
int degree=new Random().nextInt()%30;
int num=new Random().nextInt(10);
String s=num+"";
g.rotate(degree*Math.PI/180, x, HEIGHT-9);//设置旋转的角度
g.drawString(s, x, HEIGHT-9);
g.rotate(-degree*Math.PI/180, x, HEIGHT-9);
x+=30;
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值