:
, :
1. , .
2. .
3. . , , , StringBuffer , StringBuffer session , JSP .
:
PAGE :
<%@ page language="java" contentType="image/jpg;charset=gb2312" %>
:
Color getRandColor(int min,int max){ // RGB
Random random1=new Random();
if(min>=255)min=255;
if(max>=255)max=255;
int r=min+random1.nextInt(max-min);
int g=min+random1.nextInt(max-min);
int b=min+random1.nextInt(max-min);
return new Color(r,g,b);
}
//
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires",0);
// ,
int width=60,height=20; //
BufferedImage buff=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); //
Graphics g=buff.getGraphics(); //
graphics :
:
g.setColor(getRandColor(200,250));
g.fillRect(0,0,width,height);
:( )
for(int i=1;i<=30;i++){
int x=rand.nextInt(width); //
int y=rand.nextInt(height);
int tx=rand.nextInt(12);
int ty=rand.nextInt(12);
g.drawLine(x,y,x+tx,y+ty);
}
:
String coding=""; //
for(int i=0;i<4;i++){
String temp=String.valueOf(rand.nextInt(10)); //0-9
coding+=temp;
// ,20-140
g.setColor(getRandColor(20,140));
g.drawString(temp,13*i+6,16);
}
// session
session.setAttribute("code",coding);
:( , )
g.dispose();
ServletOutputStream sos=response.getOutputStream();
ImageIO.write(buff,"jpeg",sos);
sos.flush(); //
sos.close();
sos=null;
response.flushBuffer();
out.clear();
//Return a new BodyContent object, save the current "out" JspWriter, and update the value of the "out" attribute in the page scope attribute namespace of the PageContext
out=pageContext.pushBody();