JSP实现验证码(2)
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Controll", "no-cache");
response.setIntHeader("Expires",0);
//背景
BufferedImage bi = new BufferedImage(WIDTH, HEIGHT,BufferedImage.TYPE_INT_RGB);
Graphics g = bi.getGraphics();
drawBackground(g);
//随机产生验证码
char[] rands=generateCheckCode();
//System.out.println(fun(rands));
HttpSession session=request.getSession();
session.setAttribute("num",fun(rands)+"");//验证码==12-9=3;写入sesion对象
drawRands(g,rands);
ByteArrayOutputStream bos=new ByteArrayOutputStream();
ImageIO.write(bi, "JPEG", bos);
byte[] buf=bos.toByteArray();//将bi对象里面内容转化成字符
out.write(buf);
response.setContentLength(buf.length);
out.flush();
out.close();
}
private int fun(char[] rands){
int num1=Integer.parseInt(rands[0]+"")*10+Integer.parseInt(rands[1]+"");
int num2=Integer.parseInt(rands[2]+"");
int num=0;
if(rands[2]=='+'){
num=num1+num2;
}else{
num=num1-num2;
}
return num;
}
private void drawRands(Graphics g, char[] rands) {
g.setColor(Color.black);
g.setFont(new Font(null,Font.ITALIC|Font.BOLD,18));
g.drawString(" "+rands[0],1,20);
g.drawString(" "+rands[1],14,17);
g.drawString(" "+rands[3],30,16);
g.drawString(" "+rands[2],42,18);
g.drawString(" "+rands[4],56,16);
}
private char[] generateCheckCode() {
String chars="0123456789";
String char1="+-";
char[] rands=new char[5];
rands[0]=chars.charAt((int) (Math.random()*2)+1);
rands[1]=chars.charAt((int) (Math.random()*10));
rands[2]=chars.charAt((int) (Math.random()*9)+1);
rands[3]=char1.charAt((int) (Math.random()*2));
rands[4]='=';
return rands;
}
private void drawBackground(Graphics g) {
相关新闻>>
- 发表评论
-
- 最新评论 更多>>