客户端输出验证码(SpringMVC,当然用其他框架也类似)

6 篇文章 0 订阅
3 篇文章 0 订阅

在pringMVC的Controller中,我们可以用一个产生验证码的Controller方法,客户端的img标签src属性为Controller方法的请求地址

代码如下:

客户端的请求

 <body>
  	<!-- src是产生验证码的Controller方法的的RequestMapping值 -->
  	<img alt="" src="/springmvc_img/testImg.action">
  </body>
Controller

@Controller
public class GetRandomNum{
	public int width = 120;	//图片宽度
	public int height = 25;	//图片高度
	@RequestMapping("/testImg")
	public void testImg(HttpServletResponse response) throws Exception{
		BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
		Graphics2D g = (Graphics2D) image.getGraphics();

		//1、设置背景色
		setBackGround(g);
		//2、设置边框
		setBorder(g);
		//3、画干扰线
		drawRandomLine(g);
		//4、写随机数
		drawRandomNum(g);
		//设置浏览器以图片的方式打开
		response.setContentType("image/jpeg");
		//告诉浏览器不要缓存
		response.setHeader("expries","-1");
		response.setHeader("Cache-Control","no-cache");
		response.setHeader("Pragma","no-cache");
		//5、写给浏览器
		ImageIO.write(image,"jpg",response.getOutputStream());
		//没有返回值
	}
	
	//设置背景颜色
	private void setBackGround(Graphics g){
		g.setColor(Color.WHITE);
		g.fillRect(0, 0, width, height);
	}
	//设置边框
	private void setBorder(Graphics g){
		g.setColor(Color.BLUE);
		g.drawRect(1, 1, width-2, height-2);
	}
	//画干扰线
	private void drawRandomLine(Graphics g){
		g.setColor(Color.GREEN);
		for(int i = 0;i<5;i++){
			int x1 = new Random().nextInt(width);
			int y1 = new Random().nextInt(height);
			int x2 = new Random().nextInt(width);
			int y2 = new Random().nextInt(height);
			g.drawLine(x1, y1, x2, y2);
		}
	}
	//产生随机数
	private void drawRandomNum(Graphics2D g){
		//设置字体颜色
		g.setColor(Color.RED);
		//设置字体样式
		g.setFont(new Font("宋体",Font.BOLD,20));
		String base = "abcdefghijklmnopqrstuvwxyz123456789";//随机字符串
		int x = 5;//字体的位置
		for(int i = 0;i<4;i++){//产生4个随机字符
			int degree = new Random().nextInt()%30;//旋转角度
			int index = new Random().nextInt(base.length());
			
			String ch = base.charAt(index)+"";
			g.rotate(degree*Math.PI/180, x,20);
			g.drawString(ch, x, 20);
			g.rotate(-degree*Math.PI/180, x, 20);
			x+= 30;//字体位置右移30px
		}
	}
}
值得注意的是:Controller方法不能返回String类型的逻辑视图名、ModelAndView或者request.getRequestDispatcher("").forward(request, response),否者会抛出IllegalStsteException异常,因为forward(request, response)会清空响应体的内容,而向浏览器写数据过多超出缓存区的大小会调用flushBuffer()清空缓存区强制将数据写到浏览器中,所以会抛异常


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值