欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java登錄驗證碼實現(xiàn)代碼

 更新時間:2013年10月16日 16:50:15   作者:  
這篇文章介紹了java實現(xiàn)登錄驗證碼:用興趣的同學可以參考一下
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;        
    // 驗證碼字符個數(shù)        
    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";        
        // 字符個數(shù)        
        String strCodeCount = "4";        
        // 將配置的信息轉換成數(shù)值        
        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();        
        // 創(chuàng)建一個隨機數(shù)生成器類        
        Random random = new Random();        
        // 將圖像填充為白色        
        g.setColor(Color.WHITE);        
        g.fillRect(0, 0, width, height);        
        // 創(chuàng)建字體,字體的大小應該根據(jù)圖片的高度來定。        
        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數(shù)字的驗證碼。        
        for (int i = 0; i < codeCount; i++) {        
            // 得到隨機產生的驗證碼數(shù)字。        
            String strRand = String.valueOf(codeSequence[random.nextInt(36)]);        
            // 產生隨機的顏色分量來構造顏色值,這樣輸出的每位數(shù)字的顏色值都將不同。        
            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);        
            // 將產生的四個隨機數(shù)組合在一起。        
            randomCode.append(strRand);        
        }        
        // 將四位數(shù)字的驗證碼保存到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模擬服務器解析web數(shù)據(jù)

    Java模擬服務器解析web數(shù)據(jù)

    本篇文章主要給大家詳細分享了搭建JavaWeb服務器的詳細步驟以及用到的代碼,對此有需要的朋友可以跟著學習下,希望能給你帶來幫助
    2021-07-07
  • java實現(xiàn)用戶簽到BitMap功能實現(xiàn)demo

    java實現(xiàn)用戶簽到BitMap功能實現(xiàn)demo

    這篇文章主要為大家介紹了java實現(xiàn)用戶簽到BitMap功能實現(xiàn)demo,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-11-11
  • Springboot @RequestBody注解踩坑記錄

    Springboot @RequestBody注解踩坑記錄

    這篇文章主要介紹了Springboot @RequestBody注解踩坑記錄,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-03-03
  • Springboot在IDEA熱部署的配置方法

    Springboot在IDEA熱部署的配置方法

    這篇文章主要介紹了Springboot在IDEA熱部署的配置方法,給大家補充介紹了Intellij IDEA 4種配置熱部署的方法,需要的朋友可以參考下
    2018-04-04
  • springboot+camunda實現(xiàn)工作流的流程分析

    springboot+camunda實現(xiàn)工作流的流程分析

    Camunda是基于Java語言,支持BPMN標準的工作流和流程自動化框架,并且還支持CMMN規(guī)范,DMN規(guī)范,本文給大家介紹springboot+camunda實現(xiàn)工作流的流程分析,感興趣的朋友一起看看吧
    2021-12-12
  • SpringBoot整合JWT的入門指南

    SpringBoot整合JWT的入門指南

    JWT全稱是json web token,它將用戶信息加密到 token 里,服務器不保存任何用戶信息,服務器通過使用保存的密鑰驗證 token 的正確性,只要正確即通過驗證,這篇文章主要給大家介紹了關于SpringBoot整合JWT的相關資料,需要的朋友可以參考下
    2021-06-06
  • Java面向對象基礎知識之枚舉

    Java面向對象基礎知識之枚舉

    這篇文章主要介紹了Java面向對象的之枚舉,文中有非常詳細的代碼示例,對正在學習java基礎的小伙伴們有很好的幫助,需要的朋友可以參考下
    2021-11-11
  • Java遞歸實現(xiàn)菜單樹的方法詳解

    Java遞歸實現(xiàn)菜單樹的方法詳解

    這篇文章主要為大家詳細介紹了Java遞歸實現(xiàn)菜單樹的方法,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2022-03-03
  • Java中的runnable 和 callable 區(qū)別解析

    Java中的runnable 和 callable 區(qū)別解析

    Runnable接口用于定義不需要返回結果的任務,而Callable接口可以返回結果并拋出異常,通常與Future結合使用,Runnable適用于簡單的后臺任務和定時任務,而Callable適用于并行計算、異步操作和復雜任務,選擇使用哪個接口取決于具體的應用場景,感興趣的朋友一起看看吧
    2025-03-03
  • 詳解SpringCloud服務認證(JWT)

    詳解SpringCloud服務認證(JWT)

    本篇文章主要介紹了SpringCloud服務認證(JWT),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-01-01

最新評論