加入收藏 | 设为首页 | 会员中心 | 我要投稿 聊城站长网 (https://www.0635zz.com/)- 智能语音交互、行业智能、AI应用、云计算、5G!
当前位置: 首页 > 教程 > 正文

JSP上图片验证的实现

发布时间:2023-05-16 13:27:58 所属栏目:教程 来源:
导读: 图片验证在有关注册和发表留言经常用到.我在此用jsp写了个.供大家参考. 其中 com.sun.image 不是java的标准包.需要另外下载.相关地址为:

1. random.jsp (产生四位的随机字符,由0-9,a-z,a-z构成.并把最终字
 图片验证在有关注册和发表留言经常用到.我在此用jsp写了个.供大家参考.  其中 com.sun.image 不是java的标准包.需要另外下载.相关地址为:
 
1.    random.jsp  (产生四位的随机字符,由0-9,a-z,a-z构成.并把最终字符串放到session中保存以让后续页面验证真伪)
 
    代码如下:
 
<%@ page autoflush="false"  import="java.util.*,java.awt.*,java.awt.image.*,com.sun.image.codec.jpeg.*,java.util.*"%>
 
<%@ page import=""  contenttype="text/html; charset=gb2312"%>
 
<%
 
string chose="0123456789abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz";
 
char display[]={'0',' ','0',' ','0',' ','0'},ran[]={'0','0','0','0'},temp;
 
random rand=new random();
 
for(int i=0;i<4;i++)
 
{
 
 temp=chose.charat(rand.nextint(chose.length()));
 
 display[i*2]=temp;
 
 ran[i]=temp;
 
 }

string random=string.valueof(display);
 
session.setattribute("random",string.valueof(ran));
 
 %>
 
<%
 
        out.clear();
 
        response.setcontenttype("image/jpeg");
 
        response.addheader("pragma","no-cache");
 
        response.addheader("cache-control","no-cache");
 
        response.adddateheader("expries",0);
 
        int width=47, height=15;
 
        bufferedimage image = new bufferedimage(width, height, bufferedimage.type_int_rgb);
 
        graphics g = image.getgraphics();
 
        //以下填充背景颜色
 
        g.setcolor(color.green);
 
        g.fillrect(0, 0, width, height);
 
       //设置字体颜色
 
        g.setcolor(color.red);
 
        g.drawstring(random,3,10);
 
        g.dispose();
 
        servletoutputstream outstream = response.getoutputstream();
 
        jpegimageencoder encoder =jpegcodec.createjpegencoder(outstream);
 
        encoder.encode(image);
 
        outstream.close();
 
   %>
 
2.   img.jsp  (显示验证图片.由于本程序简单让验证程序也一并放在了一起)
 
  代码如下:
 
<%@ page contenttype="text/html; charset=gb2312" language="java"%>
 
<%
 
string num=request.getparameter("num");
 
string random=(string)session.getattribute("random");
 
if(num!=null&&random!=null)
 
{
 
 if(!num.equals(random))
 
 {
 
  out.println("<script>alert('验证码错误!请重试。')</script>");
 
  out.println("<script>history.go(-1)</script>");
 
  //response.sendredirect("img.jsp");
 
 }
 
 else
 
  {
 
   out.println("<center>验证成功!</center>");
 
  }
 
}
 
%>
 
<html>
 
<head>
 
<title>图片验证</title>
 
<meta http-equiv="content-type" content="text/html; charset=gb2312">
 
</head>
 
<body>
 
 <form action="img.jsp" method="post">
 
 <table>
 
  <tr>
 
   <td>
 
    <input type="text" name="num" size=10>
 
   </td>
 
   <td>
 
    <img src="random.jsp">
 
   </td>
 
  </tr>
 
 </table>
 
 <input type="submit" value="ok">
 
</form>
 
</body>
 
</html>
 
 

(编辑:聊城站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!