springmvc+谷歌图形验证码功能实现

1.拉入图形验证码得porm

<dependency>
   <groupId>com.github.penggle</groupId>
   <artifactId>kaptcha</artifactId>
   <version>2.3.2</version>
</dependency>

2.在你的springMvc得配置文件配置好谷歌验证码得bean



	<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.textproducer.font.size">45</prop>
						<prop key="kaptcha.textproducer.font.color">gray</prop>
						<prop key="kaptcha.textproducer.char.length">4</prop>
						<prop key="kaptcha.session.key">code</prop>
						<prop key="kaptcha.obscurificator.impl">com.google.code.kaptcha.impl.ShadowGimpy</prop>
					</props>
				</constructor-arg>
			</bean>
		</property>
	</bean>

3 .写一个controller(注意包扫描),因为是前后端分离,所以不能使用session得方法,所以将验证码得值存到redis中共享

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.binary.Base64;//用此将验证码转成字节传给前端
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.google.code.kaptcha.Producer;

@Controller

public class CaptchaImageCreateController {

	private Producer captchaProducer = null;

	@Autowired
	public void setCaptchaProducer(Producer captchaProducer) {
		this.captchaProducer = captchaProducer;
	}

	@Resource
	private RedisTemplate<String, String> redis;//注入redis

	@GetMapping("/kcode")
	@ResponseBody
	public Map<String, String> handleRequest(HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		response.setDateHeader("Expires", 0);
		response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		response.setHeader("Pragma", "no-cache");
		//生成验证码得值
		String capText = captchaProducer.createText();
		//生成验证码得键
		String token = UUID.randomUUID().toString();
		// 存入redis
		redis.opsForValue().set(token, capText, 5, TimeUnit.MINUTES);
		response.setHeader("code_token", token);
		BufferedImage bi = captchaProducer.createImage(capText);
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ImageIO.write(bi, "jpg", out);
		try {
			out.flush();
		} finally {
			out.close();
		}
		//放到map返回给前端展示
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("code_token", token);
		map.put("img", Base64.encodeBase64String(out.toByteArray()));//将图片转成BASE64编码字节
		return map;
	}

}

4.注意,这里返回前端的是转成base64的图片,前端需要这样显示:

<img src="data:image/png;base64,此处填base64编码"/>
基于SpringMVC annotation 的图形验证码 主要是controller的写法 实现前台验证码的显示 和刷新 验证功能相信大家都能写出来 访问 http://localhost:8080/SpringMVC_annotation_volidate/login jsp页面关键代码 function changeValidateCode(obj){ var timeNow = new Date().getTime(); obj.src="checkCode/service.do?time="+timeNow; } .. .. .. .. Controller package qianyan.mofi.controller; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/checkCode") public class CheckCodeController extends HttpServlet { public CheckCodeController() { super(); } public void destroy() { super.destroy(); } public void init() throws ServletException { super.init(); } public Color getRandColor(int s, int e) { Random random = new Random(); if (s > 255) s = 255; if (e > 255) e = 255; int r = s + random.nextInt(e - s); int g = s + random.nextInt(e - s); int b = s + random.nextInt(e - s); return new Color(r, g, b); } @RequestMapping("service.do") public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 禁止缓存 response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "No-cache"); response.setDateHeader("Expires", 0); // 指定生成的响应是图片 response.setContentType("image/jpeg"); int width = 200; int height = 60; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 创建BufferedImage类的对象 Graphics g = image.getGraphics(); // 创建Graphics类的对象 Graphics2D g2d = (Graphics2D) g; // 通过Graphics类的对象创建一个Graphics2D类的对象 Random random = new Random(); // 实例化一个Random对象 Font mFont = new Font("华文宋体", Font.BOLD, 30); // 通过Font构造字体 g.setColor(getRandColor(200, 250)); // 改变图形的当前颜色为随机生成的颜色 g.fillRect(0, 0, width, height); // 绘制一个填色矩形 // 画一条折线 BasicStroke bs = new BasicStroke(2f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL); // 创建一个供画笔选择线条粗细的对象 g2d.setStroke(bs); // 改变线条的粗细 g.setColor(Color.DARK_GRAY); // 设置当前颜色为预定义颜色中的深灰色 int[] xPoints = new int[3]; int[] yPoints = new int[3]; for (int j = 0; j < 3; j++) { xPoints[j] = random.nextInt(width - 1); yPoints[j] = random.nextInt(height - 1); } g.drawPolyline(xPoints, yPoints, 3); // 生成并输出随机的验证文字 g.setFont(mFont); String sRand = ""; int itmp = 0; for (int i = 0; i 1.1f) scaleSize = 1f; trans.scale(scaleSize, scaleSize); g2d_word.setTransform(trans); /************************/ g.drawString(String.valueOf(ctmp), 30 * i + 40, 16); } // 将生成的验证码保存到Session中 HttpSession session = request.getSession(true); session.setAttribute("randCheckCode", sRand); g.dispose(); ImageIO.write(image, "JPEG", response.getOutputStream()); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值