码迷,mamicode.com
首页 > 编程语言 > 详细

java开发篇---验证码

时间:2015-03-18 20:24:21      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:

验证码的作用:防止恶意破解密码、刷票、论坛灌水、刷页。

技术分享

有效防止某个黑客对某一个特定注册用户用特定程序暴力破解方式进行不断的登录尝试,实际上使用验证码是现在很多网站通行的方式(比如招商银行的网上个人银行,百度社区),我们利用比较简易的方式实现了这个功能。虽然登录麻烦一点,但是对网友的密码安全来说这个功能还是很有必要,也很重要。但我们还是 提醒大家要保护好自己的密码 ,尽量使用混杂了数字、字母、符号在内的6位以上密码,不要使用诸如1234之类的简单密码或者与用户名相同、类似的密码 ,免得你的账号被人盗用给自己带来不必要的麻烦。

验证码通常使用一些线条和一些不规则的字符组成,主要作用是为了防止一些黑客把密码数据化盗取。

大多数网站的验证码都是需要点击一下填写框,然后会自动弹出验证码图片击验证码旁边红色字样即可更换

由于验证码是随机产生的,有很大几率会出现无法清楚识别的验证码图片,所以需要注意的是,一般网站都会有相应的提示,如“看不清,换一张”等,如果没有提示,则直接点击当前的验证码图片,可以完成验证码的更换。

下面这将使用Jsp+Servle+JavaBean来实现验证码:

直接上代码:

RandomValidateCode.java
package com.oumyye.util;
/*
 * 作者:oumyye
 */
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class RandomValidateCode {

    public static final String RANDOMCODEKEY = "RANDOMVALIDATECODEKEY";//放到session中的key
    private Random random = new Random();
    private String randString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";//随机产生的字符串
    
    private int width = 120;//图片宽
    private int height = 40;//图片高
    private int lineSize = 40;//干扰线数量
    private int stringNum = 6;//随机产生字符数量
    /*
     * 获得字体
     */
    private Font getFont(){
        return new Font("Fixedsys",Font.CENTER_BASELINE,20);
    }
    /*
     * 获得颜色
     */
    private Color getRandColor(int fc,int bc){
        if(fc > 255)
            fc = 255;
        if(bc > 255)
            bc = 255;
        int r = fc + random.nextInt(bc-fc-16);
        int g = fc + random.nextInt(bc-fc-14);
        int b = fc + random.nextInt(bc-fc-18);
        return new Color(r,g,b);
    }
    /**
     * 生成随机图片
     */
    public void getRandcode(HttpServletRequest request,
            HttpServletResponse response) {
        HttpSession session = request.getSession();
        //BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
        Graphics g = image.getGraphics();//产生Image对象的Graphics对象,改对象可以在图像上进行各种绘制操作
        g.fillRect(0, 0, width, height);
        g.setFont(new Font("Times New Roman",Font.ROMAN_BASELINE,20));
        g.setColor(getRandColor(100, 133));
        //绘制干扰线
        for(int i=0;i<=lineSize;i++){
            drowLine(g);
        }
        //绘制随机字符
        String randomString = "";
        for(int i=1;i<=stringNum;i++){
            randomString=drowString(g,randomString,i);
        }
        session.removeAttribute(RANDOMCODEKEY);
        session.setAttribute(RANDOMCODEKEY, randomString);
        System.out.println(randomString);
        g.dispose();
        try {
            ImageIO.write(image, "JPEG", response.getOutputStream());//将内存中的图片通过流动形式输出到客户端
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /*
     * 绘制字符串
     */
    private String drowString(Graphics g,String randomString,int i){
        g.setFont(getFont());
        g.setColor(new Color(random.nextInt(101),random.nextInt(111),random.nextInt(121)));
        String rand = String.valueOf(getRandomString(random.nextInt(randString.length())));
        randomString +=rand;
        g.translate(random.nextInt(3), random.nextInt(3));
        g.drawString(rand, 13*i, 30);
        return randomString;
    }
    /*
     * 绘制干扰线
     */
    private void drowLine(Graphics g){
        int x = random.nextInt(width);
        int y = random.nextInt(height);
        int xl = random.nextInt(10);
        int yl = random.nextInt(15);
        g.drawLine(x, y, x+xl, y+yl);
    }
    /*
     * 获取随机的字符
     */
    public String getRandomString(int num){
        return String.valueOf(randString.charAt(num));
    }
}
ImageServlet .java
package com.oumyye.servlet;
/**
 * 作者:oumyye
 */
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oumyye.util.RandomValidateCode;

public class ImageServlet extends HttpServlet {

    /**
     * Constructor of the object.
     */
    public ImageServlet() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

         response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
            response.setHeader("Pragma", "No-cache");//设置响应头信息,告诉浏览器不要缓存此内容
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            RandomValidateCode randomValidateCode = new RandomValidateCode();
            try {
                randomValidateCode.getRandcode(request, response);//输出图片方法
            } catch (Exception e) {
                e.printStackTrace();
            }
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

         doGet(request, response);
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    }
}

配置文件web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>0001web</display-name>
   <servlet>
    <description>ImageCreate</description>
    <display-name>ImageCreate</display-name>
    <servlet-name>ImageServlet</servlet-name>
    <servlet-class>com.oumyye.servlet.ImageServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ImageServlet</servlet-name>
    <url-pattern>/servlet/ImageServlet</url-pattern>
  </servlet-mapping>
</web-app>

index.jsp

<!DOCTYPE html>
<html>
  <head>
    <title>验证码</title>
    <!-- Bootstrap -->
    <meta charset="utf-8"> 
    <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
    <link href="bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet" media="screen">
    <link href="assets/styles.css" rel="stylesheet" media="screen">
     <!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
    <!--[if lt IE 9]>
      <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    <script src="vendor/modernizr-2.6.2-respond-1.1.0.min.js"></script>
    
    <script type="text/javascript">
    function refresh(obj) {
        obj.src = "servlet/ImageServlet?"+Math.random();
    }
    </script>
    
    
  </head>
  <body id="login">
   
        <input type="text" placeholder="验证码" name="imageCode" id="randomCode" onblur="checkImage()" style="width:58%;" required>
        <img title="点击更换" onclick="javascript:refresh(this);" src="servlet/ImageServlet" style="margin-top:-16px;"><br/>
        <div id="checkBody">
        </div>
    <!-- /container -->
    <script src="vendors/jquery-1.9.1.min.js"></script>
    <script src="bootstrap/js/bootstrap.min.js"></script>
    <script type="text/javascript">
    
    var xmlHttp ;
    function createXMLHttpRequest(){
        if(window.ActiveXOBject){
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }else if(window.XMLHttpRequest){
            xmlHttp = new XMLHttpRequest();
        }
    }
    
    
    function checkImage(){
        var  imageCode = document.getElementById("randomCode").value;
        if(imageCode==""||imageCode==null){
            document.getElementById("checkBody").innerHTML="" +
            "<div class=‘alert alert-danger‘ role=‘alert‘>请输入验证码!</div> " ;
            document.getElementById("randomCode").focus() ;
            return false ;
        }
        
        var url = "userCheckCodeAction.action?imageCode="+imageCode;
        createXMLHttpRequest();
        xmlHttp.onreadystatechange = processorCheckImage;
        xmlHttp.open("POST",url,true);
        xmlHttp.send();
    }
    
    function processorCheckImage(){
        var responseContext ;
        if(xmlHttp.readyState==4){
            if(xmlHttp.status==200){
                responseContext = xmlHttp.responseText;
                
                if(responseContext.indexOf("failure")!=-1){
                    
                    document.getElementById("checkBody").innerHTML="" +
                    "<div class=‘alert alert-danger‘ role=‘alert‘>验证码错误!</div> " ;
                    document.getElementById("randomCode").focus() ;
                    return false ;
                }else{
                    document.getElementById("checkBody").innerHTML="" +
                            "<div class=‘alert alert-success‘ role=‘alert‘>验证码正确 !</div> " ;
                            
                    document.getElementById("submitBtn").innerHTML="" +        
                            "<button class=‘btn btn-large btn-primary‘ type=‘submit‘ style=‘width:80%;‘ >登  陆</button>" ;
                    return true ;
        }
    }
}
}

    </script>
    
    
  </body>
</html>

界面如下

技术分享

点击图片可以刷新

java开发篇---验证码

标签:

原文地址:http://www.cnblogs.com/oumyye/p/4347969.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!