熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> JSP教程 >> 正文

JSP中圖片驗證的實現[1]

2013-11-15 12:19:12  來源: JSP教程 

    [前言]:圖片驗證在有關注冊和發表留言經常用到我在此用jsp寫了個供大家參考 其中 comsunimage 不是java的標准包需要另外下載相關地址為
    http://javasuncom/products/javamedia/jai/

    randomjsp (產生四位的隨機字符azAZ構成並把最終字符串放到session中保存以讓後續頁面驗證真偽)
    代碼如下
    <%@ page autoFlush=false import=javautil*javaawt*javaawtimage*
    comsunimagecodecjpeg*javautil*%>
    <%@ page import= contentType=text/html; charset=gb%>
    <%
    String chose=
    abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ;
    char display[]={ }ran[]={}temp;
    Random rand=new Random();
    for(int i=;i<;i++)
    {
    temp=chosecharAt(randnextInt(choselength()));
    display[i*]=temp;
    ran[i]=temp;
    }
    String random=StringvalueOf(display);
    sessionsetAttribute(randomStringvalueOf(ran));
    %>
    <%
    outclear();
    responsesetContentType(image/jpeg);
    responseaddHeader(pragmaNOcache);
    responseaddHeader(CacheControlnocache);
    responseaddDateHeader(Expries);
    int width= height=;
    BufferedImage image = new BufferedImage(width height BufferedImageTYPE_INT_RGB);
    Graphics g = imagegetGraphics();

    //以下填充背景顏色
    gsetColor(ColorGREEN);
    gfillRect( width height);

    //設置字體顏色
    gsetColor(ColorRED);
    gdrawString(random);
    gdispose();
    ServletOutputStream outStream = responsegetOutputStream();
    JPEGImageEncoder encoder =JPEGCodeccreateJPEGEncoder(outStream);
    encoderencode(image);
    outStreamclose();
    %>

[]  []  


From:http://tw.wingwit.com/Article/program/Java/JSP/201311/20714.html
    推薦文章
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.