天天看點

谷歌開源的kaptcha驗證碼與SpringBoot2.0內建使用

1.pom中引入依賴

<!--kaptcha驗證碼-->
        <dependency>
            <groupId>com.github.penggle</groupId>
            <artifactId>kaptcha</artifactId>
            <version>2.3.2</version>
        </dependency>
           

2.啟動類中配置驗證碼的相關配置【也可以添加kaptchaConfig.xml中配置 然後在啟動類上在用@ImportResource(locations{"classpath:kaptchaConfig.xml"})引入即可,最後在寫這種方式的引入】

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

import java.util.Properties;

@SpringBootApplication()
@MapperScan("com.XXX.dao")
//@ImportResource(locations={"classpath:kaptchaConfig.xml"})
public class UserApplication {
    public static void main(String[] args) {
        SpringApplication.run(UserApplication.class,args);
    }
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
    @Bean
    public DefaultKaptcha getDefaultKaptcha(){
        com.google.code.kaptcha.impl.DefaultKaptcha defaultKaptcha = new com.google.code.kaptcha.impl.DefaultKaptcha();
        Properties properties = new Properties();
        properties.setProperty("kaptcha.border", "yes");
        properties.setProperty("kaptcha.border.color", "105,179,90");
        properties.setProperty("kaptcha.textproducer.font.color", "blue");
        properties.setProperty("kaptcha.image.width", "110");
        properties.setProperty("kaptcha.image.height", "40");
        properties.setProperty("kaptcha.textproducer.font.size", "30");
        properties.setProperty("kaptcha.session.key", "code");
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        properties.setProperty("kaptcha.textproducer.font.names", "宋體,楷體,微軟雅黑");
        Config config = new Config(properties);
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }
}
           

3.Controller中配置驗證碼的擷取

@Autowired
    private DefaultKaptcha captchaProducer;

 @RequestMapping("/defaultKaptcha")
    public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            //生産驗證碼字元串并儲存到session中
            String createText = captchaProducer.createText();
            logger.debug("verifyCode:" + createText);
            httpServletRequest.getSession().setAttribute("code", createText);
            System.out.println(createText + "生成的---------------------");
            //使用生産的驗證碼字元串傳回一個BufferedImage對象并轉為byte寫入到byte數組中
            BufferedImage challenge = captchaProducer.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        //定義response輸出類型為image/jpeg類型,使用response輸出流輸出圖檔的byte數組
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();

        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream =
                httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }
           

4.頁面中加載驗證碼即可【注意通路路徑 按照自己項目修改】

$(function () {
    // 重新整理驗證碼
    $("#verification").bind("click", function () {
        $(this).hide().attr('src', '/verification?random=' + Math.random()).fadeIn();
    });
});


<img id="verification" src="/verification" style="cursor: pointer;" title="看不清?換一張" />
           

Other:另一種配置方式使用xml配置kaptcha    建立kaptchaConfig.xml   在啟動類前加注解

@ImportResource(locations={"classpath:kaptchaConfig.xml"})即可不用配置Bean
           
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha">
        <property name="config">
            <bean class="com.google.code.kaptcha.util.Config">
                <constructor-arg type="java.util.Properties">
                    <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">27</prop>
                        <!--驗證碼儲存在session的key-->
                        <prop key="kaptcha.session.key">code</prop>
                        <!--驗證碼輸出的字元長度-->
                        <prop key="kaptcha.textproducer.char.length">4</prop>
                        <!--驗證碼的字型設定-->
                        <prop key="kaptcha.textproducer.font.names">宋體,楷體,微軟雅黑</prop>
                        <!--驗證碼的取值範圍-->
                        <prop key="kaptcha.textproducer.char.string">0123456789</prop>
                        <!--圖檔的樣式-->
                        <prop key="kaptcha.obscurificator.impl">com.google.code.kaptcha.impl.WaterRipple</prop>
                        <!--幹擾顔色,合法值: r,g,b 或者 white,black,blue.-->
                       <!-- <prop key="kaptcha.noise.color">white</prop>-->
                        <!--幹擾實作類-->
                        <prop key="kaptcha.noise.impl">com.google.code.kaptcha.impl.DefaultNoise</prop>
                        <!--背景顔色漸變,開始顔色-->
                        <prop key="kaptcha.background.clear.from">185,56,213</prop>
                        <!--背景顔色漸變,結束顔色-->
                        <prop key="kaptcha.background.clear.to">white</prop>
                        <!--文字間隔-->
                        <prop key="kaptcha.textproducer.char.space">3</prop>
                    </props>
                </constructor-arg>
            </bean>
        </property>
    </bean>
</beans>