在springboot中使用google图形验证码Kaptcha

原创
2017/06/27 10:50
阅读数 8K

如题。首先,在pom.xml文件中引用如下资源库:

		<dependency>
			<groupId>com.github.penggle</groupId>
			<artifactId>kaptcha</artifactId>
			<version>2.3.2</version>
			<exclusions>
				<exclusion>
					<artifactId>javax.servlet-api</artifactId>
					<groupId>javax.servlet</groupId>
				</exclusion>
			</exclusions>
		</dependency>

在系统默认classpath下面的application.properties文件中,加入图形验证码配置参数:

#图形验证码相关配置
kaptcha.border=yes
kaptcha.borderColor=105,179,90
kaptcha.textProducerFontColor=black
kaptcha.textProducerFontSize=30
kaptcha.textProducerFontNames=Arial,\u5b8b\u4f53
kaptcha.textProducerCharLength=4
kaptcha.imageWidth=100
kaptcha.imageHeight=35
kaptcha.noiseColor=green
kaptcha.noiseImpl=com.google.code.kaptcha.impl.NoNoise
kaptcha.obscurificatorImpl=com.google.code.kaptcha.impl.ShadowGimpy
kaptcha.sessionKey=kaptcha.code
kaptcha.sessionDate=kaptcha.date

 创建图形验证码的属性文件,注意,别忘记加入前缀: prefix = "kaptcha"

package com.my;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "kaptcha")
public class KaptchaProperties {
	private String border;
	private String borderColor;
	private String textProducerFontColor;
	private String textProducerFontSize;
	private String textProducerFontNames;
	private String textProducerCharLength;
	private String imageWidth;
	private String imageHeight;
	private String noiseColor;
	private String noiseImpl;
	private String obscurificatorImpl;
	private String sessionKey;
	private String sessionDate;

    // 以下省略了各个属性的getter和setter
}

然后创建将属性自动注入DefaultKaptcha的配置类KaptchaAutoConfiguration:

package com.my;

import java.util.Properties;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;

@Configuration
@EnableConfigurationProperties(KaptchaProperties.class)
public class KaptchaAutoConfiguration {
	
	@Autowired
	private KaptchaProperties kaptchaProperties;

	@Bean(name = "kaptchaProducer")
	public DefaultKaptcha getKaptchaBean() {
		
		DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
		Properties properties = new Properties();
		properties.setProperty(Constants.KAPTCHA_BORDER, kaptchaProperties.getBorder());
		properties.setProperty(Constants.KAPTCHA_BORDER_COLOR, kaptchaProperties.getBorderColor());
		properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_FONT_COLOR, kaptchaProperties.getTextProducerFontColor());
		properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_FONT_SIZE, kaptchaProperties.getTextProducerFontSize());
		properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_FONT_NAMES, kaptchaProperties.getTextProducerFontNames());
		properties.setProperty(Constants.KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, kaptchaProperties.getTextProducerCharLength());
		properties.setProperty(Constants.KAPTCHA_IMAGE_WIDTH, kaptchaProperties.getImageWidth());
		properties.setProperty(Constants.KAPTCHA_IMAGE_HEIGHT, kaptchaProperties.getImageHeight());
		properties.setProperty(Constants.KAPTCHA_NOISE_COLOR, kaptchaProperties.getNoiseColor());
		//properties.setProperty(Constants.KAPTCHA_NOISE_IMPL, kaptchaProperties.getNoiseImpl());//去掉干扰线
		properties.setProperty(Constants.KAPTCHA_OBSCURIFICATOR_IMPL, kaptchaProperties.getObscurificatorImpl());//阴影渲染效果
		properties.setProperty(Constants.KAPTCHA_SESSION_KEY, kaptchaProperties.getSessionKey());
		properties.setProperty(Constants.KAPTCHA_SESSION_DATE, kaptchaProperties.getSessionDate());
		Config config = new Config(properties);
		defaultKaptcha.setConfig(config);
		return defaultKaptcha;
	}

}

最后,在controller里,完成图片生成和图形验证码校验:

package com.my.controller;

import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.ixinnuo.uums.frame.ReturnData;

@Controller
@RequestMapping("/kaptcha")
public class KaptchaController {

	@Autowired
	private Producer kaptchaProducer;

	/**
	 * 获取验证码图片
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/getKaptchaImage",method=RequestMethod.GET)
	public ModelAndView getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
		HttpSession session = request.getSession();
		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 = kaptchaProducer.createText();

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

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

		// write the data out
		ImageIO.write(bi, "jpg", out);
		try {
			out.flush();
		} finally {
			out.close();
		}
		return null;
	}
	
	/**
	 * 检验图片验证码
	 * @param clientCode
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value="/checkKaptcha",method=RequestMethod.GET)
	public void checkKaptcha(String clientCode,HttpServletRequest request, HttpServletResponse response) throws Exception{
		ObjectMapper mapper = new ObjectMapper();
		HttpSession session = request.getSession();
		String serverCode = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=UTF-8");
		if(clientCode != null && clientCode.equalsIgnoreCase(serverCode)){
			mapper.writeValue(response.getOutputStream(), new ReturnData(0));
		}else{
			mapper.writeValue(response.getOutputStream(), new ReturnData(2004));
		}

	}
}

 

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
1 收藏
0
分享
返回顶部
顶部