(转)转载于csdn的验证码大杂烩

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page contentType="image/jpeg" import="java.awt.*,java.awt.image.*,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);
  }
%>
<%
//设置页面不缓存
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("Times New Roman",Font.PLAIN,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 sRand="";
for (int i=0;i<4;i++){
  String rand=String.valueOf(random.nextInt(10));
  sRand=sRand.concat(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("rand",sRand);


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

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

out.clear();
out = pageContext.pushBody();
%>  
  • defonds用户头像
  • defonds
  • (我只有未来没有从前)
  • 等 级:
#3楼 得分:0回复于:2009-11-23 12:56:39
多了去了
#4楼 得分:5回复于:2009-11-23 12:58:57
<%@ page language="java" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  <base href="<%=basePath%>">
    
  <title>勤工助学管理系统之登录界面</title>
    
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">   
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<style type="text/css">
body {
text-align:center;
}
div {
width:260px;  
height:200px;  
margin-top:150px;
}
.xhj {
width:130px;
height:23px;
}
</style>
<script type="text/javascript">
var str = String(Math.floor(Math.random() * 10000));
for(var i = str.length; i < 4; i++) {
str += "0";
}

function ocy() {
document.getElementById("name").focus();
document.getElementById("abc").innerHTML = str;
}

function xhj() {
if(document.getElementById("name").value == "") {
alert("请输入用户名。");
document.getElementById("name").focus();
return false;
}
if(document.getElementById("password").value == "") {
alert("请输入密码。");
document.getElementById("password").focus();
return false;
}
if(document.getElementById("yanzm").value == "") {
alert("请输入验证码。");
document.getElementById("yanzm").focus();
return false;
}
if(document.getElementById("yanzm").value != str) {
alert("对不起,验证码输入不正确,请重新输入。");
document.getElementById("yanzm").value = "";;
document.getElementById("yanzm").focus();
yll();
return false;
}
return true;
}

function liy() {
document.getElementById("name").value = "";
document.getElementById("password").value = "";
document.getElementById("name").focus();
}

function yll() {
str = String(Math.floor(Math.random() * 10000));
for(var i = str.length; i < 4; i++) {
str += "0";
}
document.getElementById("abc").innerHTML = str;
}
</script>
  </head>
   
  <body οnlοad="ocy()" style="background-color: #CCDDEE;">
<div style="width: 370px; height: 280px;">
<form action="login.do" method="post" οnsubmit="return xhj()">
<font style="color:red; font-weight:900;">${loginn}</font> <%-- 给出用户直观提示 --%>
<table width="100%" height="100%" border="1" cellpadding="0" cellspacing="0">
<tr style="text-align: center;">
<td colspan="2">勤工助学管理系统</td>
</tr>
<tr>
<td style="width: 70px;">用户名:</td>
<td><input type="text" name="loginName" size="15" id="name" class="xhj"/></td>
</tr>
<tr>
<td>密 码:</td>
<td><input type="password" name="loginPassword" size="15" id="password" class="xhj"/></td>
</tr>
<tr>
<td>验证码:</td>
<td>
<input type="text" name="yanzm" id="yanzm" size="15" class="xhj">&nbsp;
<span id="abc" style="color: red; font-weight:900; background-color: #FFFFFF;"></span>&nbsp;
<a href="javascript:yll()" style="text-decoration: none; font-family: '新宋体';">看不清?换一个!</a>
</td>
</tr>
<tr>
<td>角 色:</td>
<td>
<input type="radio" name="loginRole" value="1" checked="checked">管理员&nbsp;&nbsp;&nbsp;
<input type="radio" name="loginRole" value="2">招聘者&nbsp;&nbsp;&nbsp;
<input type="radio" name="loginRole" value="3">求职者
</td>
</tr>
<tr style="text-align: center;">
<td colspan="2">
<input type="submit" name="btn" value="登 录" />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="reset" name="btn" value="重 置" οnclick="liy()" />
</td>
</tr>
<tr style="text-align: center;">
<td colspan="2">
<font>
<a href="register.jsp" style="text-decoration: none;font-family: 新宋体;">你还没有账户?快注册一个吧!</a>
</font>
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
#5楼 得分:5回复于:2009-11-23 13:00:05
Java code
              
              
<% @ page contentType = " text/html;charset=UTF-8 " 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); } %> <% // 设置页面不缓存 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( " Times New Roman " , Font.PLAIN, 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 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( " validCode " , sRand); // 图象生效 g.dispose(); // 输出图象到页面 ImageIO.write(image, " JPEG " , response.getOutputStream()); // response.getOutputStream()和~Response.getWriter相冲突 // 会抛出java.lang.IllegalStateException: // getOutputStream() has already been called for this response // 所以一定要加入下面这两行 out.clear(); out = pageContext.pushBody(); %>



上面是jsp页面中的验证码

下面是servlet中的验证码
Java code
 
package comm;

import java.awt.Color; 
import java.awt.Font; 
import java.awt.Graphics2D; 
import java.awt.image.BufferedImage; 
import java.util.Random; 
import javax.imageio.ImageIO; 
import javax.servlet.ServletException; 
import javax.servlet.ServletOutputStream; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import javax.servlet.http.HttpSession;


public class ImageServlet extends HttpServlet {

private static final long serialVersionUID = 1L; 
 
//验证码值
private static String value;

    // 验证码图片的宽度。 
    private int width = 63; 
    // 验证码图片的高度。 
    private int height = 20; 
    // 验证码字符个数 
    private int codeCount = 4; 
 
    // 字体高度 
    private int fontHeight;   
   
    // 验证码随机数字
    char[] codeSequence = { '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', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; 
 
    /** 
    * 初始化验证图片属性 
    */ 
    public void init() throws ServletException { 
        // 从web.xml中获取初始信息 
        // 宽度 
        String strWidth = this.getInitParameter("width"); 
        // 高度 
        String strHeight = this.getInitParameter("height"); 
        // 字符个数 
        String strCodeCount = this.getInitParameter("codeCount"); 
 
        // 将配置的信息转换成数值 
        try { 
            if (strWidth != null && strWidth.length() != 0) { 
                width = Integer.parseInt(strWidth); 
            } 
            if (strHeight != null && strHeight.length() != 0) { 
                height = Integer.parseInt(strHeight); 
            } 
            if (strCodeCount != null && strCodeCount.length() != 0) { 
                codeCount = Integer.parseInt(strCodeCount); 
            } 
        } catch (NumberFormatException e) { 
        } 
   
        fontHeight = height - 2; 
 
    } 
 
    protected void service(HttpServletRequest req, HttpServletResponse resp) 
            throws ServletException, java.io.IOException { 
 
        HttpSession session = req.getSession(); 
         
        // 定义图像buffer 
        BufferedImage buffImg = new BufferedImage(width, height, 
                BufferedImage.TYPE_INT_RGB); 
        Graphics2D g = buffImg.createGraphics(); 
 
        // 创建一个随机数生成器类 
        Random random = new Random(); 
 
        // 将图像填充随即背景颜色 (指定范围)
        g.setColor(getRandColor(200, 250)); 
        g.fillRect(0, 0, width, height); 
 
        // 创建字体,字体的大小应该根据图片的高度来定。 
        Font font = new Font("Fixedsys", Font.PLAIN, fontHeight); 
        // 设置字体。 
        g.setFont(font); 
 
        // 画边框。   
        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);
    }   
 
        // randomCode用于保存随机产生的验证码,以便用户登录后进行验证。 
        StringBuffer randomCode = new StringBuffer(); 
        int red = 0, green = 0, blue = 0; 
 
        // 随机产生codeCount数字的验证码。 
        for (int i = 0; i < codeCount; i++) { 
            // 得到随机产生的验证码数字。 
            String strRand = String.valueOf(codeSequence[random.nextInt(36)]); 
            // 产生随机的颜色分量来构造颜色值,这样输出的每位数字的颜色值都将不同。 
            // 用随机产生的颜色将验证码绘制到图像中。 
            g.setColor(new Color(20 + random.nextInt(110), 20 + random
    .nextInt(110), 20 + random.nextInt(110)));
            g.drawString(strRand, 13 * i + 6, 16);   
 
            // 将产生的四个随机数组合在一起。 
            randomCode.append(strRand); 
        } 
        // 将四位数字的验证码保存到Session中。 
        session.setAttribute("validateCodeRecruit", randomCode.toString()); 
        value = randomCode.toString();
        // 禁止图像缓存。 
        resp.setHeader("Pragma", "no-cache"); 
        resp.setHeader("Cache-Control", "no-cache"); 
        resp.setDateHeader("Expires", 0); 
 
        resp.setContentType("image/jpeg"); 
 
        //清空缓存 
        g.dispose(); 
         
        // 将图像输出到Servlet输出流中。 
        ServletOutputStream sos = resp.getOutputStream(); 
        ImageIO.write(buffImg, "jpeg", sos); 
        sos.close(); 
       
        //前台js中无法或得最新的验证码,如果要在前台js中获得session中的最新验证码值,需要用ajax来得到最新的值
        //页面加载的时候首先加载的是js代码,那时候session中值还没有更新,而js无法进入后台
    } 
   
  //给定范围获得随机颜色
    private static Random random = new Random();
   
    /**
    * 得到随即颜色(指定范围)
    * @param fc
    * @param bc
    * @return
    */
private Color getRandColor(int fc, int bc) {
int interval = fc;
if (fc > 255) {
fc = 255;
}
if (bc > 255) {
bc = 255;
}
int r = fc + random.nextInt(bc - interval);
int g = fc + random.nextInt(bc - interval);
int b = fc + random.nextInt(bc - interval);
return new Color(r, g, b);
}
   
    /**
    * ajax验证图片验证码 (页面使用此验证图片验证码是否正确,返回Boolean)
    * @param imgvalue
    * @return
    */
    public boolean getValidateValue(String imgvalue){
    //转换为统一的大写比较,用户可以不用管大小写
    return imgvalue.toUpperCase().equals(value);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值