Joke Collection Website - Blessing messages - 如何用JSP生成验证码?

如何用JSP生成验证码?

& lt% @ page language = " Java " content type = " text/html;charset=GBK

& lt% @ page import = " java.awt. * " % & gt

& lt% @ page import = " Java . awt . image . * " % & gt;

& lt% @ page import = " Java . util . * " % & gt;

& lt% @ page import = " javax . imageio . * " % & gt;

& lt%!

Color getRandColor(int fc,int BC){

Random r = new Random();

如果(fc & gt255)

fc = 255;

如果(bc & gt255)

BC = 255;

int red = fc+r . nextint(BC-fc);

int green = fc+r . nextint(BC-fc);

int blue = fc+r . nextint(BC-fc);

返回新颜色(红色、绿色、蓝色);}

% & gt

& lt%

//设置页面不缓存

response.setHeader("Pragma "," No-cache ");

response . set header(" Cache-Control "," no-Cache ");

response . setdate header(" Expires ",);

//下面开始了-生成图像

Random r = new Random();

int width = 6,height = 2

BufferedImage pic = new buffered image(宽度,高度,buffered image。TYPE _ INT _ RGB);

Graphics GC = pic . get Graphics();

gc.setColor(getRandColor(2,25));

gc.fillRect(,,width,height);

gc.setFont(新字体(" Times New Roman ",字体。平原,18));

gc.setColor(getRandColor(16,2));

for(int I = ;我& lt2;i++){

int x1 = r . nextint(width);

int y1 = r . nextint(height);

int x2 = r . nextint(15);

int y2 = r . nextint(15);

gc.drawLine(x1,y1,x2,y2);gc.setColor(getRandColor(12,24));

for(int I = ;我& lt1;i++){

int x = r . nextint(width);

int y = r . nextint(height);

gc.drawOval(x,y,,);}

String rs =

String rn =

for(int I = ;我& lt4;i++){

rn = string . value of(r . nextint(1));

RS+= rn;

GC . set Color(new Color(2+r.nextInt(11),2+r . nextint(11),2+r . nextint(11));

gc.drawString(rn,13*i+6,16);}

gc.dispose()。

try {

session . set attribute(" code ",RS);//设置会议的属性密码为生成的验证码(字符串类型),JSP中一般靠会议等来传递并获得参数} catch(Throwable t){

getServletContext()。log(t . getmessage());//这里是写日志,但要抓异常

}

ImageIO.write(pic," JPEG ",response . get output stream());//输出图片到一页面,就是流

out . clear();//后面一定要关闭流,因为在其他页面会有冲突

out = pagecontext . popbody();

% & gt

上面时code.jsp

另一页面只写一句话就能看到图片:

& ltimg src = " code.jsp " & gt

因为code.jsp可以向某个jsp页面输送一个图片,当然是验证码图片~