jsp頁面驗證碼demo_JSP編程

來源:互聯網
上載者:User

在java後台中產生驗證碼的ImageIO傳到前端頁面顯示,同時把驗證碼的value值傳入session 中用於與使用者輸入的驗證碼進行匹配,在使用者驗證中使用ajax技術,在不重新整理頁面的同時進行驗證碼驗證。

程式結構圖:

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>

結果顯示:

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.