圖形驗證碼實現方案(解決短信轟炸問題)


       最近收到leader的一個郵件說我們的項目有短信轟炸風險。頓時讓一個做技術開發的人為之一顫。今天給大家介紹一個解決這個問題的使用工具。

就是谷歌的 kaptcha 進行驗證碼生成和校驗。閑話少說直接上代碼。

1. 首先下載一個工具包

<dependency>
    <groupId>com.github.axet</groupId>
    <artifactId>kaptcha</artifactId>
    <version>0.0.9</version>
</dependency>

 

2. 建立一個spring工程填寫相關代碼。 兩個方法一個是獲取圖形驗證碼 一個是用於驗證。

@Controller
@RequestMapping("/kaptcha")
public class kaptchaController {
    @Autowired
    private Producer captchaProducer = null;

    @RequestMapping("/getKaptchaImage")
    public ModelAndView getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        String code = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        System.out.println("******************驗證碼是: " + code + "******************");

        response.setDateHeader("Expires", 0);

        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");

        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");

        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");

        // return a jpeg
        response.setContentType("image/jpeg");

        // create the text for the image
        String capText = captchaProducer.createText();

        // store the text in the session
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);

        // create the image with the text
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();

        // write the data out
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
        return null;
    }
    @RequestMapping("/check")
    public String check(HttpServletRequest request){
        //從session中取出servlet生成的驗證碼text值
        String kaptchaExpected = (String)request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
        //獲取用戶頁面輸入的驗證碼
        String kaptchaReceived = request.getParameter("kaptcha");
        //校驗驗證碼是否正確
        if (kaptchaReceived == null || !kaptchaReceived.equalsIgnoreCase(kaptchaExpected)){
            return "false";
        }
        return "true";
    }
    @RequestMapping("/index")
    public String index(HttpServletRequest request){
        return "kaptcha";
    }

}

3. springmvc.xml中加上配置。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:task="http://www.springframework.org/schema/task"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--指明 controller 所在包,並掃描其中的注解-->
    <context:component-scan base-package="com.mzq" />
    <!-- 靜態資源(js、image等)的訪問 -->
    <mvc:default-servlet-handler/>

    <!-- 通過annotation-driven可以替代下邊的處理器映射器和適配器 -->
    <mvc:annotation-driven />
    <!--靜態資源解析 -->
    <mvc:resources mapping="/js/**" location="/WEB-INF/js/" />
    <mvc:resources mapping="/css/**" location="/WEB-INF/css/" />
    <mvc:resources mapping="/img/**" location="/WEB-INF/img/" />



    <!--ViewResolver 視圖解析器-->
    <!--用於支持Servlet、JSP視圖解析-->
    <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!-- 定義統一異常處理器 -->
    <bean class="com.mzq.exception.MyExceptionResolver"></bean>
    
<!-- 
kaptcha.border.color   邊框顏色   默認為Color.BLACK  
kaptcha.border.thickness  邊框粗細度  默認為1  
kaptcha.producer.impl   驗證碼生成器  默認為DefaultKaptcha  
kaptcha.textproducer.impl   驗證碼文本生成器  默認為DefaultTextCreator  
kaptcha.textproducer.char.string   驗證碼文本字符內容范圍  默認為abcde2345678gfynmnpwx  
kaptcha.textproducer.char.length   驗證碼文本字符長度  默認為5  
kaptcha.textproducer.font.names    驗證碼文本字體樣式  默認為new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize)  
kaptcha.textproducer.font.size   驗證碼文本字符大小  默認為40  
kaptcha.textproducer.font.color  驗證碼文本字符顏色  默認為Color.BLACK  
kaptcha.textproducer.char.space  驗證碼文本字符間距  默認為2  
kaptcha.noise.impl    驗證碼噪點生成對象  默認為DefaultNoise  
kaptcha.noise.color   驗證碼噪點顏色   默認為Color.BLACK  
kaptcha.obscurificator.impl   驗證碼樣式引擎  默認為WaterRipple  
kaptcha.word.impl   驗證碼文本字符渲染   默認為DefaultWordRenderer  
kaptcha.background.impl   驗證碼背景生成器   默認為DefaultBackground  
kaptcha.background.clear.from   驗證碼背景顏色漸進   默認為Color.LIGHT_GRAY  
kaptcha.background.clear.to   驗證碼背景顏色漸進   默認為Color.WHITE  
kaptcha.image.width   驗證碼圖片寬度  默認為200  
kaptcha.image.height  驗證碼圖片高度  默認為50   
 -->
    <bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha">  
        <property name="config">  
            <bean class="com.google.code.kaptcha.util.Config">  
                <constructor-arg>  
                    <props>
                        <prop key="kaptcha.border">no</prop>
                        <prop key="kaptcha.border.color">105,179,90</prop>
                        <prop key="kaptcha.textproducer.font.color">black</prop>
                        <prop key="kaptcha.image.width">100</prop>
                        <prop key="kaptcha.image.height">40</prop>
                        <prop key="kaptcha.textproducer.font.size">30</prop>
                        <prop key="kaptcha.session.key">code</prop>
                        <prop key="kaptcha.textproducer.char.length">4</prop>
                        <prop key="kaptcha.textproducer.font.names">宋體,楷體,微軟雅黑</prop>
                    </props>
                </constructor-arg>  
            </bean>  
        </property>
        </bean>

</beans>

4. 寫一個JSP頁面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!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">  
<script type="text/javascript" src="../js/jquery-1.11.0.min.js"></script>  
<!-- <script type="text/javascript" src="../js/functions.js"></script>   -->
  
  
<title>測試頁面</title>  
<script type="text/javascript">  
$(function(){         
    $('#kaptchaImage').click(function () {//生成驗證碼  
     $(this).hide().attr('src', '../kaptcha/getKaptchaImage?' + Math.floor(Math.random()*100) ).fadeIn();  
     event.cancelBubble=true;  
    });  
});   
  
  
window.onbeforeunload = function(){  
    //關閉窗口時自動退出  
    if(event.clientX>360&&event.clientY<0||event.altKey){     
        alert(parent.document.location);  
    }  
};  
  
  
function changeCode() {  
    $('#kaptchaImage').hide().attr('src', '../kaptcha/getKaptchaImage?' + Math.floor(Math.random()*100) ).fadeIn();  
    event.cancelBubble=true;  
}  
</script>  
</head>  
<body>  
          
<div class="chknumber">
      <form action="../kaptcha/check">
      <label>驗證碼:  
      <input name="kaptcha" type="text" id="kaptcha" maxlength="4" class="chknumber_input" />
            </label>
            <br />
      <img src="../kaptcha/getKaptchaImage" id="kaptchaImage"  style="margin-bottom: -3px"/>  
      <a href="#" onclick="changeCode()">看不清?換一張</a>
      <input type="submit" value="提交">
      </form>

</div>  
</body>  
</html>  

 5. web.xml中別忘了加載這個springmvc.xml文件

  <display-name>Archetype Created Web Application</display-name>
  <servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    <async-supported>true</async-supported>
  </servlet>
  <servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <!-- 配置SESSION超時,單位是分鍾 -->
  <session-config>
    <session-timeout>15</session-timeout>
  </session-config>
<!-- Spring和mybatis的配置文件 -->
  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <!-- 防止Spring內存溢出監聽器 -->
  <listener>
    <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
  </listener>

6. 啟動項目后和效果如下。

7. 項目源碼希望大家來探討。

https://github.com/owenma/kaptcha_demo

 

如果覺得有疑問或者對你有幫助 歡迎評論。

作者:森林木馬

  如果您覺得閱讀本文對您有幫助,請點一下“推薦”按鈕,您的“推薦”將是我最大的寫作動力!歡迎各位轉載,但是未經作者本人同意 

轉載文章之后必須在 文章頁面明顯位置給出作者和原文連接否則保留追究法律責任的權利。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM