java验证码实现

验证码的作用 就不多说了 直接看效果吧



package com.shangdi.naxincameraserver.webpage;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
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("/verfycode")
public class VerifyCode {

	public static final int WIDTH = 165;// 生成的图片的宽度
	public static final int HEIGHT = 36;// 生成的图片的高度

	@RequestMapping(value="/code")
	public void getVerifyCode(HttpServletRequest request,
			HttpServletResponse response) {

		
		// 设置响应头通知浏览器以图片的形式打开
		response.setContentType("image/jpeg");// 等同于response.setHeader("Content-Type",
												// "image/jpeg");
		// 设置响应头控制浏览器不要缓存
		response.setDateHeader("expries", -1);
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Pragma", "no-cache");
		
		// 1.在内存中创建一张图片
		BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
				BufferedImage.TYPE_INT_RGB);
		// 2.虚拟画笔得到图片
		Graphics g = image.getGraphics();
		// 3.设置图片的背影色
		setBackGround(g);
		// 4.设置图片的边框
		setBorder(g);
		// 5.在图片上画干扰线
		drawRandomLine(g);
		// 6.写在图片上随机数
		String random = drawRandomNum((Graphics2D) g);// 生成数字和字母组合的验证码图片

		// 7.将随机数存在session中
		HttpSession session=request.getSession(true);
		session.setAttribute("checkcode", random);
		//两分钟之内失效
		session.setMaxInactiveInterval(2*60);

		// 8.将图片写给浏览器
		try {
			ImageIO.write(image, "jpg", response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 设置图片的背景色
	 * 
	 * @param g
	 */
	private void setBackGround(Graphics g) {
		// 设置颜色
		g.setColor(Color.WHITE);
		// 填充区域
		g.fillRect(0, 0, WIDTH, HEIGHT);
	}

	/**
	 * 设置图片的边框
	 * 
	 * @param g
	 */
	private void setBorder(Graphics g) {
		// 设置边框颜色
		g.setColor(Color.WHITE);
		// 边框区域
		g.drawRect(1, 1, WIDTH - 2, HEIGHT - 2);
	}

	/**
	 * 在图片上画随机线条
	 * 
	 * @param g
	 */
	private void drawRandomLine(Graphics g) {
		// 设置颜色
//		g.setColor(Color.GREEN);
		Random r=new Random();
		// 设置线条个数并画线
		for (int i = 0; i < 10; i++) {
			int x1 = r.nextInt(WIDTH);
			int y1 = r.nextInt(HEIGHT);
			int x2 = r.nextInt(WIDTH);
			int y2 = r.nextInt(HEIGHT);
			g.drawLine(x1, y1, x2, y2);
			//设置干扰线颜色
			Color color = new Color(20 + r.nextInt(210), 20 + r.nextInt(210), 20 + r.nextInt(210));
			g.setColor(color);
		}

	}

	/**
	 * 画随机字符
	 * 
	 * @param g
	 */
	private String drawRandomNum(Graphics2D g) {
		// 设置颜色
		g.setColor(Color.RED);
		// 设置字体
		g.setFont(new Font("宋体", Font.BOLD, 30));
		
		// 数字和字母的组合
		String baseNumLetter = "Aa0Bb1CcDd3EeFf5Gg6HhJjKkLl7MmN9nOoPp8QqRrSs2TtUuVv4WwXxYyZz";
		return createRandomChar(g, baseNumLetter);
	}

	/**
	 * 创建随机字符
	 * 
	 * @param g
	 * @param baseChar
	 * @return 随机字符
	 */
	private String createRandomChar(Graphics2D g, String baseChar) {
		StringBuffer sb = new StringBuffer();
		 Random r=new Random();
		int x = 5;
		String ch = "";
		// 控制字数
		for (int i = 0; i < 4; i++) {
			// 设置字体旋转角度
			int degree = r.nextInt() % 30;
			ch = baseChar.charAt(new Random().nextInt(baseChar.length())) + "";
			//设置随机数的颜色
			 Color color = new Color(20 + r.nextInt(210), 20 + r.nextInt(210), 20 + r.nextInt(210));  
	           g.setColor(color); 
			sb.append(ch);
			// 正向角度
			g.rotate(degree * Math.PI / 180, x, 30);
			g.drawString(ch, x, 20);
			// 反向角度
			g.rotate(-degree * Math.PI / 180, x, 30);
			x += 30;
		}
		return sb.toString();
	}
}

页面展示

	<img src="<%=basePath %>verfycode/code" id="valcode" οnclick="refresh(this,'<%=basePath %>verfycode/code')">
	
	<script type="text/javascript">
		function refresh(thisobj,path){
			//Math.random();避免客户端浏览器使用缓存
			thisobj.src=path+"?"+Math.random();
		}
	</script>


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值