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

JSP中圖片驗證是如何實現

2022-06-13   來源: JSP教程 

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

      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("random"StringvalueOf(ran));
 %>
<%

  outclear();
        responsesetContentType("image/jpeg");
        responseaddHeader("pragma""NOcache");
        responseaddHeader("CacheControl""nocache");
        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();
   %>

     imgjsp  (顯示驗證圖片由於本程序簡單讓驗證程序也一並放在了一起)

  代碼如下:

  <%@ page contentType="text/html; charset=gb" language="java"%>
<%
String num=requestgetParameter("num");
String random=(String)sessiongetAttribute("random");

  if(num!=null&&random!=null)
{
 if(!numequals(random))
 {
  outprintln("<script>alert(驗證碼錯誤!請重試)</script>");

  outprintln("<script>historygo()</script>");

  //responsesendRedirect("imgjsp");
 }
 else
  {
   outprintln("<center>驗證成功!</center>");
  }
}
%>
<html>
<head>
<title>圖片驗證</title>
<meta httpequiv="ContentType" content="text/html; charset=gb">
</head>

  <body>
 <form action="imgjsp" method="post">
 <table>
  <tr>
   <td>
    <input type="text" name="num" size=>
   </td>
   <td>
    <img src="randomjsp">
   </td>
  </tr>
 </table>
 <input type="submit" value="OK">
</form>
</body>
</html>

  
 


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