Spring 학습 - 이미지 인증 코드 생 성

27069 단어 스프링 기술
오늘 은 인증 코드 생 성 을 배우 고 싶 습 니 다. 전에 만들어 진 spring 프레임 에 demo 를 썼 습 니 다. 디 테 일 코드 를 붙 이 겠 습 니 다. 하지만 spring 의 설정 은 소개 되 지 않 습 니 다.전체 코드 가 필요 하면 연락 주세요!프론트 페이지 에서 백 스테이지 까지 완전한 설명 을 실현 합 니 다. 1: 프론트 데스크 의 코드, image. jsp
"java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>       title>
<script type="text/javascript" src="${pageContext.request.contextPath }/static/js/jquery-1.10.2.min.js">script>
head>
<body>

    <form action="##" method='post'>
            <input type="hidden" id="userId" name="userId" value=""> 
                <div class="form-group">
                    <div class="email controls">
                        <input type="text" name='loginName' id="loginName" placeholder="   " value="" class='form-control'/>
                    div>
                div>
                <div class="form-group">
                    <div class="pw controls">
                        <input type="password" autocomplete="off" id="pwd" name="pwd" placeholder="  " class='form-control'/>
                    div>
                div>

                <div class="form-group">
                    <div class="email controls">
                        <input id="validateCode" onblur="checkImg(this.value)" name="validateCode" type="text" class="form-control" placeholder="     "/>   
                    div>
                    <span class="y_yzimg"><img id="codeValidateImg"  onClick="javascript:flushValidateCode();"/>span>
                    <p class="y_change"><a href="javascript:flushValidateCode();"  >   a>p>
                div>

                <div class="form-group">
                    <span class="text-danger">span>
                div>

                <div class="submit">
                    <div class="remember">

                                <input type="checkbox" name="remember" value="1" class='icheck-me' data-skin="square" data-color="blue" id="remember">

                        <label for="remember">   label>
                    div>
                    <input type="button" value="  " onclick="javascript:submitForm();" class='btn btn-primary'>
                div>
            form>

<script type="text/javascript">
$(document).ready(function() {
     flushValidateCode();//            
   });

/*         */
function flushValidateCode(){
var validateImgObject = document.getElementById("codeValidateImg");
validateImgObject.src = "${pageContext.request.contextPath }/getSysManageLoginCode?time=" + new Date();
}
/*           */
function checkImg(code){
    var url = "${pageContext.request.contextPath}/checkimagecode";
    $.get(url,{"validateCode":code},function(data){
        if(data=="ok"){
            alert("ok!")
        }else{
            alert("error!")
            flushValidateCode();
        }
    })
}

script>

body>
html>

2: 배경 코드 ImageGenController. java
package com.dufyun.springmvc.web.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dufy.javaweb.test.RandomValidateCode;

@Controller
public class ImageGenController {


    @RequestMapping(value="/toImg")
    public String toImg(){

        return "image/image";
    }


    //       
    @RequestMapping("/getSysManageLoginCode")
    @ResponseBody
    public String getSysManageLoginCode(HttpServletResponse response,
            HttpServletRequest request) {
        response.setContentType("image/jpeg");//       ,             
        response.setHeader("Pragma", "No-cache");//        ,            
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Set-Cookie", "name=value; HttpOnly");//  HttpOnly  ,  Xss  
        response.setDateHeader("Expire", 0);
        RandomValidateCode randomValidateCode = new RandomValidateCode();
        try {
            randomValidateCode.getRandcode(request, response,"imagecode");//       
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    //     
    @RequestMapping(value = "/checkimagecode")
    @ResponseBody
    public String checkTcode(HttpServletRequest request,HttpServletResponse response) {
        String validateCode = request.getParameter("validateCode");
        String code = null;
        //1:  cookie        
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if ("imagecode".equals(cookie.getName())) {
                code = cookie.getValue();
                break;
            }
        }
        //1:  session      
        //String code1 = (String) request.getSession().getAttribute("");
        //2:         
        if(!StringUtils.isEmpty(validateCode) && validateCode.equals(code)){
            return "ok";    

        }
        return "error";
        //                  ,           !
    }

}

3: 인증 코드 를 만 드 는 도구 클래스 RandomValidateCode. java
package com.dufy.javaweb.test;


import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Random;

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


public class RandomValidateCode {
    private Random random = new Random();
    private String randString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";//         

    private int width = 80;//    
    private int height = 26;//    
    private int lineSize = 40;//      
    private int stringNum = 4;//         

    /*
     *     
     */
    private Font getFont() {
        return new Font("Fixedsys", Font.CENTER_BASELINE, 18);
    }

    /*
     *     
     */
    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);
    }

    /*
     *      
     */
    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, 16);
        return randomString;
    }

    /*
     *      
     */
    private void drowLine(Graphics g) {
        int x = random.nextInt(width);
        int y = random.nextInt(height);
        int xl = random.nextInt(13);
        int yl = random.nextInt(15);
        g.drawLine(x, y, x + xl, y + yl);
    }

    /*
     *        
     */
    public String getRandomString(int num) {
        return String.valueOf(randString.charAt(num));
    }


    /**
     *       
     */
    public void getRandcode(HttpServletRequest request,HttpServletResponse response,String key) {

        // 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, 18));
        g.setColor(getRandColor(110, 133));
        //      
        for (int i = 0; i <= lineSize; i++) {
            drowLine(g);
        }
        //       
        String randomString = "";
        for (int i = 1; i <= stringNum; i++) {
            randomString = drowString(g, randomString, i);
        }
        //1:           Cookie 
        Cookie cookie = new Cookie(key,randomString);
        response.addCookie(cookie);
        //2:           session 
        String sessionid = request.getSession().getId();
        request.getSession().setAttribute(sessionid+key, randomString);
        System.out.println("*************" + randomString);

        //  :          ,
        //(1):  cookie   ,            ,   !     。
        //(2):  session   ,               ,      ,         ,                ,        。     。
        //           ,     ,         ,             ,      ,                    。
        g.dispose();
        try {
            ByteArrayOutputStream tmp = new ByteArrayOutputStream();
            ImageIO.write(image, "png", tmp);
            tmp.close();
            Integer contentLength = tmp.size();
            response.setHeader("content-length", contentLength + "");
            response.getOutputStream().write(tmp.toByteArray());//                    
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                response.getOutputStream().flush();
                response.getOutputStream().close();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    }

}

4: 정리 인증 코드 는 여러 곳 에서 만 날 수 있 고 실현 하 는 방법 과 형식 도 많 습 니 다. 주요 목적 은 안전 을 위해 악의 적 인 공격 을 방지 하 는 것 입 니 다.당신 이 뭔 가 를 배 울 수 있 기 를 바 랍 니 다. 만약 안에 모 르 는 곳 이 있다 면 저 에 게 메 시 지 를 남기 거나 직접 연락 하 세 요!우리 가 함께 발전 하 기 를 바 랍 니 다!
5: 원본 주소: springmvc 에 들 어가 면 인증 코드 원본 주소 생 성
나의 csdn 블 로 그 를 방문 한 것 을 환영 합 니 다. 우 리 는 함께 성장 합 니 다!
"뭘 하 든 버 티 면 달라 져! 길에서 비굴 하지 도 거만 하지 도 않 아!"
블 로그 첫 페이지:http://blog.csdn.net/u010648555

좋은 웹페이지 즐겨찾기