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

jsp页面验证码demo

程序员文章站 2022-07-12 08:26:56
在java后台中生成验证码的imageio传到前端页面显示,同时把验证码的value值传入session 中用于与用户输入的验证码进行匹配,在用户验证中使用ajax技术,在...

在java后台中生成验证码的imageio传到前端页面显示,同时把验证码的value值传入session 中用于与用户输入的验证码进行匹配,在用户验证中使用ajax技术,在不刷新页面的同时进行验证码验证。

程序结构图:

jsp页面验证码demo

verifycodeutils程序主要内容为通过java生成验证码的图片,以及验证码的value值,程序如下:

package utils;

import java.awt.color;
import java.awt.font;
import java.awt.graphics2d;
import java.awt.image.bufferedimage;
import java.util.hashmap;
import java.util.map;
import java.util.random;

public class verifycodeutils {
private static bufferedimage image = null;

  private static random random = new random();
  //在自己定义的一些数中,生成4位随机数
  public static string getverifycode() {
    string str = "";
    char[] code = new char[]{'a','b','c','d','e','f','g','h','i','j','k','l','m','n','p','q','r','s','t','u',
      'v','w','x','y','z','a','b','c','d','e','f','g','h','i','j','k','m','n','p','q','r','s','t',
      'u','v','w','x','y','z','2','3','4','5','6','7','8','9'};
    random random = new random();
    for(int i = 0; i < 4; i++) {
      str += string.valueof(code[random.nextint(code.length)]);
    }
    return str;
  }

  //生成验证码图像
  public static map getverifycode(int width, int heigth) {
    verifycodeutils.image = new bufferedimage(width, heigth, bufferedimage.type_int_rgb);
    graphics2d g = (graphics2d) verifycodeutils.image.getgraphics();
    string verifycode = getverifycode();
    map map = new hashmap();
    map.put("verifycode", verifycode);
    //将图像填充为白色
    g.setcolor(color.white);
    g.fillrect(0, 0, width, heigth);
    //设置字体
    g.setfont(new font("宋体", font.bold + font.italic, heigth-10));
    //画边框。 
    g.setcolor(verifycodeutils.getcolor());  
    g.drawrect(0, 0, width, heigth); 
    //随机产生干扰线,使图象中的认证码不易被其它程序探测到
    g.setcolor(color.black);  
    for (int i = 0; i < 50; i++) {  
      int x = verifycodeutils.random.nextint(width);  
      int y = verifycodeutils.random.nextint(heigth);  
      int xl = verifycodeutils.random.nextint(5);  
      int yl = verifycodeutils.random.nextint(5); 
      g.setcolor(getcolor());
      g.drawline(x, y, x + xl, y + yl);  
    } 

    char c;
    for(int i = 0; i < 4; i++) {
      c = verifycode.charat(i);
      g.drawstring(c+"", i*20+40, heigth-10);
    }
    map.put("image", verifycodeutils.image);
    return map;
  }

  //随机化颜色
  public static color getcolor() {
    int red = 0, green = 0, blue = 0;  
    // 产生随机的颜色分量来构造颜色值,这样输出的每位数字的颜色值都将不同。  
    red = verifycodeutils.random.nextint(255);  
    green = verifycodeutils.random.nextint(255);  
    blue = verifycodeutils.random.nextint(255); 
    return new color(red,green,blue);
  }
}

verifycodeservlet把verifycodeutils生成的验证码图片通过io流传入前端显示,代码如下:

package servlet;

import java.awt.image.bufferedimage;
import java.io.ioexception;
import java.util.map;

import javax.imageio.imageio;
import javax.servlet.servletexception;
import javax.servlet.annotation.webservlet;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;

import utils.verifycodeutils;


/**
 * servlet implementation class verifycodeservlet
 */
@webservlet("/")
public class verifycodeservlet extends httpservlet {
  private static final long serialversionuid = 1l;

  /**
   * @see httpservlet#httpservlet()
   */
  public verifycodeservlet() {
    super();
    // todo auto-generated constructor stub
  }

  /**
   * @see httpservlet#doget(httpservletrequest request, httpservletresponse response)
   */
  protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
    response.setheader("expires", "-1");
    response.setheader("cache-control", "no-cache");
    response.setheader("pragma", "no-cache");
    response.setheader("content-type", "image/jpeg");
    map map = verifycodeutils.getverifycode(223, 50);
    //把verifycode的数值传入session中用于验证用户输入的验证码是否正确
    request.getsession().setattribute("verifycode", map.get("verifycode").tostring().touppercase());
    //通过io流传入前端显示
    imageio.write((bufferedimage) map.get("image"), "jpg", response.getoutputstream()); 
  }

  /**
   * @see httpservlet#dopost(httpservletrequest request, httpservletresponse response)
   */
  protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
    // todo auto-generated method stub
    doget(request, response);
  }

}

页面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">
<base id="base" href="${pagecontext.request.contextpath}">
<title>验证码测试界面</title>
<style>
div{float:left;}
input{width:223px;height:31px;margin-right:20px;}
img{width:223px;height:35px;}
p{margin:10px;}
</style>
</head>
 <body>
 <script src="${pagecontext.request.contextpath}/js/demo.js"></script>
 <div>
  <input type="text" name="verifycode" id="verifycode" placeholder="验证码" onblur="check_verifycode()">
  </div>
  <div>
    <img src="${pagecontext.request.contextpath}/servlet/verifycodeservlet" style="width: 100%" onclick="this.src=this.src + '?' + math.random()"/>
  </div>
  <div>
    <p id = "tip"></p>
  </div>
</body>

</html>

js 实现ajax代码如下:

/**
 * 
 */
function check_verifycode(){
  var xmlhttpreqverifycode = null;
  var url =document.getelementbyid("base").href +"/servlet/testverifycodeservlet";
  var verifycode = document.getelementbyid("verifycode").value;
  var tip = document.getelementbyid("tip");
  var errortip = "输入的验证码不正确";
  var successtip = "输入的验证码正确";
  tip.innerhtml=errortip;
  if(verifycode==null || verifycode==""){
    tip.innerhtml=errortip;
    tip.style.color = "red";
  }else{
    if(window.xmlhttprequest) {
      //dom2浏览器
      xmlhttpreqverifycode = new xmlhttprequest();
    } else if(window.activexobject) {  
      //使用json语法创建数组
      var msxml = ['msxml2.xmlhttp.5.0', 'msxml2.xmlhttp.4.0', 'msxml2.xmlhttp.3.0', 'msxml2.xmlhttp', 'microsoft.xmlhttp'];
      for(var i = 0; i < msxml.length; i++) {
        try{
          xmlhttpreqverifycode = new activexobject(msxml[i]);
        } catch(e) {

        }
      }
    }
    xmlhttpreqverifycode.open("post",url, true);
    xmlhttpreqverifycode.setrequestheader("content-type", "application/x-www-form-urlencoded");
    xmlhttpreqverifycode.onreadystatechange = function testverifycodeservletresponse(){
      if(xmlhttpreqverifycode.readystate == 4 && (xmlhttpreqverifycode.status == 200 || xmlhttpreqverifycode.status == 304)) {
        if(xmlhttpreqverifycode.responsetext == 1){
          tip.innerhtml = successtip;
          tip.style.color = "green";
        }else if(xmlhttpreqverifycode.responsetext == 0){
          tip.innerhtml = errortip;
          tip.style.color = "red";
        }
      }
    }
    xmlhttpreqverifycode.send("code="+verifycode);
  }  
  //ajax前后台交互
function createxmlhttprequest(xmlhttpreq) {
  if(window.xmlhttprequest) {
    //dom2浏览器  
    xmlhttpreq = new xmlhttprequest();
  } else if(window.activexobject) {
    //使用json语法创建数组
    var msxml = ['msxml2.xmlhttp.5.0', 'msxml2.xmlhttp.4.0', 'msxml2.xmlhttp.3.0', 'msxml2.xmlhttp', 'microsoft.xmlhttp'];
    for(var i = 0; i < msxml.length; i++) {
      try{
        xmlhttpreq = new activexobject(msxml[i]);
      } catch(e) {

      }
    }

    return xmlhttpreq;
  }
}

}

testverifycodeservlet与js交互代码为:

package servlet;

import java.io.ioexception;
import java.io.printwriter;

import javax.servlet.servletexception;
import javax.servlet.annotation.webservlet;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;

/**
 * servlet implementation class testverifycodeservlet
 */
@webservlet("/testverifycodeservlet")
public class testverifycodeservlet extends httpservlet {
  private static final long serialversionuid = 1l;

  /**
   * @see httpservlet#httpservlet()
   */
  public testverifycodeservlet() {
    super();
    // todo auto-generated constructor stub
  }

  /**
   * @see httpservlet#doget(httpservletrequest request, httpservletresponse response)
   */
  protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
    // todo auto-generated method stub

    string codetrue = (string) request.getsession().getattribute("verifycode");
    string codeinput = request.getparameter("code");
    system.out.println(codeinput);
    response.setcontenttype("text/html;charset=utf-8");
    printwriter out = response.getwriter();//打印流
    if(codeinput!=null){
      if(codeinput.touppercase().equals(codetrue)){
        out.println("1");
      }else{
        out.println("0");
      }
    }

  }

  /**
   * @see httpservlet#dopost(httpservletrequest request, httpservletresponse response)
   */
  protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
    // todo auto-generated method stub
    doget(request, response);
  }

}

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" xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
 <display-name></display-name>
 <welcome-file-list>
  <welcome-file>demo.jsp</welcome-file>
 </welcome-file-list>
 <servlet>
  <servlet-name>verifycodeservlet</servlet-name>
  <servlet-class>servlet.verifycodeservlet</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>verifycodeservlet</servlet-name>
  <url-pattern>/servlet/verifycodeservlet</url-pattern>
 </servlet-mapping>
  <servlet>
  <servlet-name>testverifycodeservlet</servlet-name>
  <servlet-class>servlet.testverifycodeservlet</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>testverifycodeservlet</servlet-name>
  <url-pattern>/servlet/testverifycodeservlet</url-pattern>
 </servlet-mapping>
</web-app>

结果显示:

jsp页面验证码demo

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。