JSP驗證碼

<%@  page  contentType="p_w_picpath/jpeg" %>
<%@  page import ="java.awt.*, java.awt.p_w_picpath.*"%>
<%@  page import ="java.util.* , javax.p_w_picpathio.*"%>
<%!
//產生隨機顏色函數getRandColor
Color  getRandColor (int  fc , int  bc){
    Random  r=new  Random();
    if(fc>255)  fc=255;
    if(bc>255)   bc=255;
    int red=fc+r.nextInt(bc-fc);
    int green=fc+r.nextInt(bc-fc);
    int blue=fc+r.nextInt(bc-fc);
    return new Color(red,green,blue);
}
%>
<%
//設置頁面不緩存
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
response.setHeader("Expires",0);
//建立隨機類
Random r=new Random();
//在內存中建立圖像,寬爲width,高爲height
int  width=60 , height=20;
BufferedImage  pic= new  BufferedImage(width , height , BufferedImage_TYPE_INT_RGB);
//獲取圖形上下文環境
Graphics  gc=pic.getGraphics();
//設定背景顏色並進行填充
gc.setColor(getRandColor(200,250));
gc.fillRect(0,0,width,height);
//設定圖形上下文環境字體
gc.setFont(new Font("Times New Roman", Font.PLAIN , 18));
//隨機產生200條幹擾直線,使圖像中的認證碼不被其餘分析程序探測到
gc.setColor(getRandColor(160,200));
for(int  i=0;i<200;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, x1+x2 , y1+y2);
}
//隨機產生100個干擾點,使圖像不易被其餘分析程序探測到
gc.setColor(getRandColor(120,240));
for(int i=0;i<100;i++){
    int x=r.nextInt(width);
    int y=r.nextInt(height);
    gc.drawOval(x , y , 0 , 0);
}
//隨機產生4位數字的驗證碼
String  RS="" , rn="";
for(int i=0;i<4;i++){
    //產生10之內的隨機數字rn
    rn=String.valueOf(r.nextInt(10));
    RS+=rn;
    //將驗證碼用drawString 函數顯示在圖像裏
    gc.drawString(rn , 13*i+6 , 16);
//釋放圖形上下文環境
gc.dispose();
//將驗證碼RS存入SESSION 中共享
session.setAttribute("random" , RS);
//輸出生成後的驗證碼圖像到頁面
ImageIO.write(pic , "JPEG" , response.getOutputStream());
%>
相關文章
相關標籤/搜索