验证码实现

1、验证码 jsp ajax

String contextPath = request.getContextPath();

String imgsrc = contextPath + "/inc/verifyCodeImage.jsp";

<%--若出现outMemery的错误,则缓存太小--%>
<%@ page buffer="32kb" %>  

<tr>
    <td align="right"><span
     style="font-size: 13px; font-style: normal; color: #000000"> 
    <%=UtilTools.getLabelResource("AU_VERIFYCODE", currentLocale)%>  </span></td>
    <td height="28"><input type="text" name="verifycode"
     onkeydown="javascript:login();" style="font-size: 13px" size="2">  

  <img align="top" src="<%=imgsrc%>" onclick="resetImg($(this))"></td>
   </tr>

function resetImg(ogj){
 ogj.attr("src","<%=imgsrc%>?"+Math.random()*10);
  
}


 

<%--校验验证码--%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%@ page import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*" pageEncoding="UTF-8" %>

<%!
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);
        }
%>
<%
//设置页面不缓存
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires", 0);

// 在内存中创建图象
int width=60, height=20;
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("serif",Font.BOLD,18));

//画边框
//g.setColor(new Color());
//g.drawRect(0,0,width-1,height-1);


// 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
g.setColor(getRandColor(160,200));
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);
}

// 取随机产生的认证码(4位数字)
//String rand = request.getParameter("rand");
//rand = rand.substring(0,rand.indexOf("."));
String strVerifyCode="";
for (int i=0;i<4;i++){
    String rand=String.valueOf(random.nextInt(10));
    strVerifyCode+=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(Constants.SESSION_VERIFYCODE,strVerifyCode);
//System.out.println(strVerifyCode);

// 图象生效
g.dispose();

// 输出图象到页面
ImageIO.write(image, "JPEG", response.getOutputStream());

out.clear(); 
out = pageContext.pushBody(); 

%> 

2、验证码-struts2

http://hi.baidu.com/tommyhi/item/892e4ccd2c4b9a09ad092fcb 转

1、  Action代码 2、 Result 类

package stu.struts2.image;

 

import com.opensymphony.xwork2.ActionSupport;

import java.util.Random;

import java.awt.*;

import java.awt.image.*;

import java.io.ByteArrayOutputStream;

 

import org.apache.struts2.ServletActionContext;

 

public class ImageAction extends ActionSupport {

    /**

     * 验证码对应的Session名

     */

    private static final String SessionName = "CheckCodeImageAction";

    /**

     * 用于随机生成验证码的数据源

     */

    private static final char[] source = new char[]{

       'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',

       'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 

       'U', 'V', 'W', 'X', 'Y', 'Z',

       '1', '2', '3', '4', '5', '6', '7', '8', '9', '0'

    };

    /**

     * 用于随机打印验证码的字符颜色

     */

    private static final Color[] colors = new Color[]{

       Color.RED, Color.BLUE, Color.BLACK

    };

    /**

     * 用于打印验证码的字体

     */

    private static final Font font = new Font("宋体", Font.PLAIN, 13);

    /**

     * 用于生成随机数的随机数生成器

     */

    private static final Random rdm = new Random();

    

    private String text = "";

    

    private byte[] bytes = null;

    private String contentType = "image/png";

    

    public byte[] getImageBytes(){

       return this.bytes;

    }

    public String getContentType(){

       return this.contentType;

    }

    

    public void setContentType(String value){

       this.contentType = value;

    }

    

    public int getContentLength(){

       return bytes.length;

    }

    

    /**

     * 生成长度为4的随机字符串

     */

    private void generateText(){

       char[] source = new char[4];

       for(int i=0; i<source.length; i++){

           source[i] = ImageAction.source[rdm.nextInt(ImageAction.source.length)];

       }

       this.text = new String(source);

       // 设置Session

       ServletActionContext.getRequest().getSession().setAttribute(SessionName, this.text);

    }

    

    /**

     * 在内存中生成打印了随机字符串的图片

     * @return 在内存中创建的打印了字符串的图片

     */

    private BufferedImage createImage(){

       int width = 35;

       int height = 14;

       

       BufferedImage image = 

           new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

       

       Graphics g = image.getGraphics();

       g.setColor(Color.LIGHT_GRAY);

       g.fillRect(0, 0, width, height);

       

       g.setFont(font);

       for(int i=0; i<this.text.length(); i++){

           g.setColor(colors[rdm.nextInt(colors.length)]);

           g.drawString(this.text.substring(i, i+1), 2 + i * 8, 12);

       }

       g.dispose();

       

       return image;

    }

    

    /**

     * 根据图片创建字节数组

     * @param image 用于创建字节数组的图片

     */

    private void generatorImageBytes(BufferedImage image){

       ByteArrayOutputStream bos = new ByteArrayOutputStream();

       try{

           javax.imageio.ImageIO.write(image, "jpg", bos);

           this.bytes = bos.toByteArray();

       }catch(Exception ex){

       }finally{

           try{

              bos.close();

           }catch(Exception ex1){

           }

       }

    }

 

    /**

     * 被struts2过滤器调用的方法

     * @return 永远返回字符串"image"

     */

    public String doDefault(){

       

       this.generateText();

       BufferedImage image = this.createImage();

       this.generatorImageBytes(image);

       

       return "image";

    }

}

package stu.struts2.image;

import com.opensymphony.xwork2.ActionInvocation;

import com.opensymphony.xwork2.Result;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

 

public class ImageResult implements Result {

 

    public void execute(ActionInvocation ai) throws Exception {

       

       ImageAction action = (ImageAction)ai.getAction();

       

       HttpServletResponse response = ServletActionContext.getResponse();

       response.setHeader("Cash", "no cash");

       response.setContentType(action.getContentType());

       response.setContentLength(action.getContentLength());

       response.getOutputStream().write(action.getImageBytes());

       response.getOutputStream().flush();

    }

}


3、  struts.xml 配置文件

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts SYSTEM "struts-2.1.dtd" >

<struts>

    <include file="/struts-default.xml" />

   

    <package namespace="/test" name="testPackage" extends="struts-default">

       <result-types>

           <result-type name="ValidateImage" class="stu.struts2.image.ImageResult" />

       </result-types>

       <action name="ValidateImage" class="stu.struts2.image.ImageAction" method="doDefault">

           <result name="image" type="ValidateImage" />

       </action>

    </package>

</struts>

应该可以不需要重定义一个Result类型。有时间回去看下。另在jsp页面里这样使用:

<script type="text/javascript">
     function changeValidateCode(obj) {
         //获取当前的时间作为参数,无具体意义
         var timenow = new Date().getTime();
         //每次请求需要一个不同的参数,否则可能会返回同样的验证码
         //可能和浏览器的缓存机制有关系
         obj.src="test/ValidateImage?d="+timenow;
     }
 </script>

<input type="text"><img src="test/ValidateImage" onClick="changeValidateCode(this)">


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值