欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java登录验证码实现代码

程序员文章站 2023-12-18 22:33:46
verifycodeservlet.java类:复制代码 代码如下:package com.spring.controller;import java.awt.color;...
verifycodeservlet.java类:
复制代码 代码如下:

package com.spring.controller;
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; 
import org.springframework.stereotype.controller;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestmethod;
@controller
public class verifycodeservlet extends httpservlet {
  // 验证码图片的宽度。        
    private int width = 60;        
    // 验证码图片的高度。        
    private int height = 20;        
    // 验证码字符个数        
    private int codecount = 4;        
    private int x = 0;        
    // 字体高度        
    private int fontheight;        
    private int codey;        
    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 initxuan() throws servletexception {        
        // 从web.xml中获取初始信息        
        // 宽度        
        string strwidth ="80";        
        // 高度        
        string strheight ="30";        
        // 字符个数        
        string strcodecount = "4";        
        // 将配置的信息转换成数值        
        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) {        
        }        
        x = width / (codecount + 1);        
        fontheight = height - 2;        
        codey = height - 4;        
    }  
    @requestmapping(value="xuan/verifycode",method=requestmethod.get)
    public void service(httpservletrequest req, httpservletresponse resp)        
            throws servletexception, java.io.ioexception {
        initxuan();
        // 定义图像buffer        
        bufferedimage buffimg = new bufferedimage(width, height,        
                bufferedimage.type_int_rgb);        
        graphics2d g = buffimg.creategraphics();        
        // 创建一个随机数生成器类        
        random random = new random();        
        // 将图像填充为白色        
        g.setcolor(color.white);        
        g.fillrect(0, 0, width, height);        
        // 创建字体,字体的大小应该根据图片的高度来定。        
        font font = new font("fixedsys", font.plain, fontheight);        
        // 设置字体。        
        g.setfont(font);        
        // 画边框。        
        g.setcolor(color.black);        
        g.drawrect(0, 0, width - 1, height - 1);        
        // 随机产生160条干扰线,使图象中的认证码不易被其它程序探测到。        
        g.setcolor(color.black);        
        for (int i = 0; i < 10; 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)]);        
            // 产生随机的颜色分量来构造颜色值,这样输出的每位数字的颜色值都将不同。        
            red = random.nextint(255);        
            green = random.nextint(255);        
            blue = random.nextint(255);        
            // 用随机产生的颜色将验证码绘制到图像中。        
            g.setcolor(new color(red, green, blue));        
            g.drawstring(strrand, (i + 1) * x, codey);        
            // 将产生的四个随机数组合在一起。        
            randomcode.append(strrand);        
        }        
        // 将四位数字的验证码保存到session中。        
        httpsession session = req.getsession();        
        session.setattribute("validatecode", randomcode.tostring());        
        // 禁止图像缓存。        
        resp.setheader("pragma", "no-cache");        
        resp.setheader("cache-control", "no-cache");        
        resp.setdateheader("expires", 0);        
        resp.setcontenttype("image/jpeg");        
        // 将图像输出到servlet输出流中。        
        servletoutputstream sos = resp.getoutputstream();        
        imageio.write(buffimg, "jpeg", sos);        
        sos.close();        
    }        
}

resultservlet.java:
复制代码 代码如下:

package com.spring.controller;
import java.io.ioexception;        
import java.io.printwriter;        
import javax.servlet.servletexception;               
import javax.servlet.http.httpservletrequest;        
import javax.servlet.http.httpservletresponse;
import org.springframework.stereotype.controller;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestmethod;
@controller
public class resultservlet {
     @requestmapping(value="resultservlet/validatecode",method=requestmethod.post)
     public void dopost(httpservletrequest request, httpservletresponse response)        
             throws servletexception, ioexception {        
         response.setcontenttype("text/html;charset=utf-8");        
         string validatec = (string) request.getsession().getattribute("validatecode");        
         string verycode = request.getparameter("c");        
         printwriter out = response.getwriter();        
         if(verycode==null||"".equals(verycode)){        
             out.println("验证码为空");        
         }else{        
             if(validatec.equals(verycode)){        
                 out.println("验证码正确");        
             }else{        
                 out.println("验证码错误");        
             }        
         }        
         out.flush();        
         out.close();        
     }        
}

jsp页面:
复制代码 代码如下:

<%@ page language="java" contenttype="text/html; charset=utf-8"      
    pageencoding="utf-8"%>      
<!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd">      
<html>      
    <head>      
        <meta http-equiv="content-type" content="text/html; charset=utf-8">
        <title>test verify code</title> 
    </head> 
    <body>      
        <input id="verycode" name="verycode" type="text"/>      
        <img id="imgobj"  alt="" src="xuan/verifycode"/>      
        <a href="#" onclick="changeimg()">换一张</a>      
        <input type="button" value="验证" onclick="isrightcode()"/>      
        <div id="info"></div>      
    </body>      
</html>
<script type="text/javascript">
 function changeimg(){    
    var imgsrc = $("#imgobj");    
    var src = imgsrc.attr("src");    
    imgsrc.attr("src",chgurl(src));    
}    
//时间戳    
//为了使每次生成图片不一致,即不让浏览器读缓存,所以需要加上时间戳    
function chgurl(url){    
    var timestamp = (new date()).valueof();    
    urlurl = url.substring(0,17);    
    if((url.indexof("&")>=0)){    
        urlurl = url + "×tamp=" + timestamp;    
    }else{    
        urlurl = url + "?timestamp=" + timestamp;    
    }    
    return url;    
}    
function isrightcode(){    
    var code = $("#verycode").attr("value");    
    code = "c=" + code;    
    $.ajax({    
        type:"post",    
        url:"resultservlet/validatecode",    
        data:code,    
        success:callback    
    });    
}    
function callback(data){    
    $("#info").html(data);    

</script> 

运行效果:
java登录验证码实现代码

上一篇:

下一篇: