1. 程式人生 > >Google Kaptcha驗證碼的使用

Google Kaptcha驗證碼的使用

buffer word light nal mave ets ttr ref jpg

原文:http://www.kailing.pub/article/index/arcid/92.html

Kaptcha是什麽?

kaptcha 是谷歌開源的非常實用的驗證碼生成工具,基於SimpleCaptcha的開源項目。使用Kaptcha 生成驗證碼十分簡單並且參數可以進行自定義。只需添加jar包配置下就可以使用,通過配置,可以自己定義驗證碼大小、顏色、顯示的字符等等。下面就來講一下如何使用kaptcha生成驗證碼以及在服務器端取出驗證碼進行校驗。

怎麽使用Kaptcha?

1.首先要項目使用Kaptcha肯定要依賴kaptcha的jar,maven項目的話直接加入如下依賴,非maven項目就自己下載jar包吧

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

官方下載鏈接:https://code.google.com/archive/p/kaptcha/downloads,當然你得FQ哈

2.配置kaptcha

以項目使用spring為例,配置一個默認的Kaptcha的bean,如下

	<bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha" scope="singleton">
	    <property name="config">
	        <bean class="com.google.code.kaptcha.util.Config">
	            <constructor-arg>
	                <props>
	                	<prop key="kaptcha.session.key">kaptcha.code</prop>  
	                	<!-- 無邊框 -->
	                    <prop key="kaptcha.border">no</prop>
	                    <prop key="kaptcha.textproducer.font.color">black</prop>
	                    <!-- 渲染效果:水紋:WaterRipple;魚眼:FishEyeGimpy;陰影:ShadowGimpy -->
	                    <prop key="kaptcha.obscurificator.impl">com.google.code.kaptcha.impl.WaterRipple</prop>
	                    <!-- 不要噪點 -->
	                    <prop key="kaptcha.noise.impl">com.google.code.kaptcha.impl.NoNoise</prop>
	                    <prop key="kaptcha.image.width">90</prop>
	                    <prop key="kaptcha.image.height">33</prop>
	                    <prop key="kaptcha.textproducer.font.size">25</prop>
	                    <prop key="kaptcha.textproducer.char.length">4</prop>
	                    <prop key="kaptcha.textproducer.char.space">5</prop>
	                    <!-- 和登錄框背景顏色一致 -->
	                    <prop key="kaptcha.background.clear.from">247,247,247</prop>
	                    <prop key="kaptcha.background.clear.to">247,247,247</prop>
	                </props>
	            </constructor-arg>
	        </bean>
	    </property>
	</bean>

3.將生成的驗證碼保存進session中,並輸出由驗證碼生成的圖片流到頁面

        @Autowired
	private Producer captchaProducer;
	@RequestMapping(value = "/kaptchaImage", method = RequestMethod.GET)
    public void kaptcha(HttpServletRequest req, HttpServletResponse rsp) {
		ServletOutputStream out = null;
		try {
	        HttpSession session = req.getSession();
	        rsp.setDateHeader("Expires", 0);
	        rsp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
	        rsp.addHeader("Cache-Control", "post-check=0, pre-check=0");
	        rsp.setHeader("Pragma", "no-cache");
	        rsp.setContentType("image/jpeg");
	        String capText = captchaProducer.createText();
	        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
	        BufferedImage image = captchaProducer.createImage(capText);
	        out = rsp.getOutputStream();
	        ImageIO.write(image, "jpg", out);
	        out.flush();
        }catch(IOException e)
		{
			throw new SystemException(e);
		} finally {
            try {
				out.close();
			} catch (IOException e) {
				throw new SystemException(e);
			}
        }
    }

4.校驗用戶輸入的驗證碼和保存進session的是否一直,達到驗證目的

@RequestMapping(value = "/login", method = RequestMethod.POST, produces = "text/html; charset=utf-8")
	public String userLogin(String accountName, String password, String captcha, Boolean rememberMe, HttpServletRequest request) {
		 //從session中取出kaptcha生成的驗證碼text值
	        String expected = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
	        //獲取用戶頁面輸入的驗證碼
	        if(!captcha.equalsIgnoreCase(expected))
	        {
	        	request.setAttribute("error", "驗證碼錯誤!");
				return "/login";
	        }else
	        {
                    xxxx驗證碼後的後續邏輯
                 }
}

更詳細的Kaptcha驗證碼配置?

  • kaptcha.border 是否有邊框 默認為true 我們可以自己設置yes,no
  • 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

效果圖如下

技術分享

Google Kaptcha驗證碼的使用