用jsp实现随机验证码

来源:互联网 发布:封面设计 知乎 编辑:程序博客网 时间:2024/06/09 23:42

在这里用jsp实现随机验证码其实就是java类一样,只不过方便调用而已吐舌头

<%@ page contentType="image/jpeg" import="java.awt.*, java.awt.image.*,java.util.*,javax.imageio.*" %><%!
  //定义一个随机数的颜色方法  Color getRandColor(int fc,int bc)  {    Random random = new Random();    if(fc>255) fc=255;    if(bc>255) bc=255;    int r=fc+random.nextInt(bc-fc);    int g=fc+random.nextInt(bc-fc);    int b=fc+random.nextInt(bc-fc);    return new Color(r,g,b);  }%><%
  <span style="font-family: Arial; font-size: 14px; line-height: 26px;">//禁止图像缓存。</span> 
  out.clear();//这句针对resin服务器,如果是tomacat可以不要这句  response.setHeader("Pragma","No-cache");  response.setHeader("Cache-Control","no-cache");  response.setDateHeader("Expires", 0);
  //定义高度和宽度
  int width=60, height=20;
<span style="font-family: Arial; font-size: 14px; line-height: 26px;">   //定义图像buffer</span>  BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  Graphics g = image.getGraphics();  Random random = new Random();  g.setColor(getRandColor(200,250));  g.fillRect(0, 0, width, height);  g.setFont(new Font("Times New Roman",Font.PLAIN,18));  g.setColor(getRandColor(160,200));
<span style="font-family: Arial; font-size: 14px; line-height: 26px;">    //随机产生155条干扰线,使图象中的认证码不易被其它程序探测到。</span>  for (int i=0;i<155;i++)  {    int x = random.nextInt(width);    int y = random.nextInt(height);    int xl = random.nextInt(12);    int yl = random.nextInt(12);    g.drawLine(x,y,x+xl,y+yl);  }  String sRand="";  for (int i=0;i<4;i++){    String rand=String.valueOf(random.nextInt(10));    sRand+=rand;    g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));    g.drawString(rand,13*i+6,16);  }  //将认证码存入SESSION  session.setAttribute("AUTH_CODE",sRand);  g.dispose();
<span style="font-family: Arial; font-size: 14px; line-height: 26px;">  //将图像输出到response输出流中。</span>  ImageIO.write(image, "JPEG", response.getOutputStream());%>
//下面是jsp调用
<input type="text" name="rand" maxlength="4" id="rand"  size="10" class="rand"><img alt="code..." name="randImage" id="randImage" src="image.jsp" width="40" height="25" border="1" align="absmiddle"><a href="javascript:loadimage();" tabindex="-1" style="font-size: 10px"  title='看不清点我'>看不清</a>

0 0
原创粉丝点击