Java 生成验证码

Java 生成验证码

直接上代码

  1. 先创建好一个生成图片的类。
public class VerCode {
	private BufferedImage img = new BufferedImage(100, 50, BufferedImage.TYPE_INT_RGB);
	Color[] colors = new Color[]{Color.RED,Color.blue,Color.YELLOW,Color.green,Color.pink,Color.gray,Color.orange};
	public Map<BufferedImage,String> createGrap(){
		
		String randWord = "";
		
		Random random = new Random();
		List<Integer> words = new ArrayList<>();
		for(int i = 0; i < 4; i++){
			words.add(random.nextInt(10));
			
			randWord += words.get(i);
		}
		
		Graphics2D gra = img.createGraphics();
		
		gra.setColor(Color.white);
		
		gra.fillRect(0, 0, 100, 50);
		
		gra.setFont(new Font("微软雅黑",Font.ITALIC|Font.BOLD,20));
		
		for(int i = 0; i <5 ;i++){
			gra.setColor(colors[random.nextInt(colors.length)]);
			gra.drawLine(0, random.nextInt(51), 100, random.nextInt(51));
		}
		for(int i = 0; i <10 ;i++){
			gra.setColor(colors[random.nextInt(colors.length)]);
			gra.drawOval(random.nextInt(101), random.nextInt(51), 2, 2);
		}
		for(int i = 0; i < words.size();i++){
			gra.setColor(colors[random.nextInt(colors.length)]);
			gra.drawString(words.get(i)+"", i*20, 35+(random.nextInt(11)-5));
		}
		
		
		Map<BufferedImage,String> map = new HashMap<>();
		map.put(img, randWord);
		
		return map;
		
	}
}
  1. 在Cotroller中调用该类
 @Controller
public class VerCodeController {

	@RequestMapping("/pages/Vcode")
	public String vercode(HttpServletRequest req, HttpServletResponse res) throws IOException {
		BufferedImage img = null;
		String words = "";
		VerCode verCode = new VerCode();
		Map<BufferedImage, String> grap = verCode.createGrap();

		for (Entry<BufferedImage, String> arg : grap.entrySet()) {
			img = arg.getKey();
			words = arg.getValue();
		}
		System.out.println("Code:"+words);
		ServletOutputStream outputStream = res.getOutputStream();

		ImageIO.write(img, "jpg", outputStream);

		HttpSession session = req.getSession();

		session.setAttribute("vercode", words);

		return null;
	}
}

3.前端页面图片请求

<a href=""><img src="Vcode" onClick="this.src=this.src+'?'+Math.random()"/></a>

后面的onClick方法可以实现在不刷新页面的情况下重新加载图片。
总结:
前端页面加载时候,会向后端发送Vcode请求,被Controller控制器响应后,在控制器内把图片转换成流放入返回数据流中,在将验证码放入session中以便登入时候的验证。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值