首页>代码>SpringMVC+Mybatis整合实现简单权限控制系统代码>/pelDem/src/com/flf/controller/SecCodeController.java
package com.flf.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;

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

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.flf.util.Const;

/**
 * @author Administrator
 * 验证码生成类
 */
@Controller
@RequestMapping("/code")
public class SecCodeController {

	@RequestMapping
	public void generate(HttpSession session,HttpServletResponse response){
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		String code = drawImg(output);
		session.setAttribute(Const.SESSION_SECURITY_CODE, code); //放入session
		//System.out.println(session.getAttribute(Const.SESSION_SECURITY_CODE));
		try {
			ServletOutputStream out = response.getOutputStream();
			output.writeTo(out);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private String drawImg(ByteArrayOutputStream output){
		String code = "";
		for(int i=0; i<4; i++){
			code += randomChar();
		}
		int width = 70;
		int height = 25;
		BufferedImage bi = new BufferedImage(width,height,BufferedImage.TYPE_3BYTE_BGR);
		Font font = new Font("Times New Roman",Font.PLAIN,20);
		Graphics2D g = bi.createGraphics();
		g.setFont(font);
		Color color = new Color(66,2,82);
		g.setColor(color);
		g.setBackground(new Color(226,226,240));
		g.clearRect(0, 0, width, height);
		FontRenderContext context = g.getFontRenderContext();
		Rectangle2D bounds = font.getStringBounds(code, context);
		double x = (width - bounds.getWidth()) / 2;
		double y = (height - bounds.getHeight()) / 2;
		double ascent = bounds.getY();
		double baseY = y - ascent;
		g.drawString(code, (int)x, (int)baseY);
		g.dispose();
		try {
			ImageIO.write(bi, "jpg", output);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return code;
	}
	
	private char randomChar(){
		Random r = new Random();
		String s = "ABCDEFGHJKLMNPRSTUVWXYZ0123456789";
		return s.charAt(r.nextInt(s.length()));
	}
}
最近下载更多
 LV7 3月25日
1379585889  LV11 2023年6月7日
孟子大叔  LV7 2023年3月27日
hihhhh  LV6 2022年12月18日
ming_123_9715  LV23 2022年7月19日
wanglinddad  LV54 2022年4月7日
鹿先森  LV3 2022年2月17日
mynewcode  LV5 2022年2月9日
Liang  LV3 2021年6月23日
gshnbb  LV9 2021年6月16日
最近浏览更多
uid0901  LV2 4月2日
1437047954 3月7日
暂无贡献等级
xuweiwowzy  LV5 1月14日
bjlabc  LV1 1月4日
weibo1003 2023年10月25日
暂无贡献等级
irivn007  LV15 2023年10月19日
漫步的海星  LV4 2023年9月21日
2036495585  LV9 2023年9月20日
aaaaooa  LV4 2023年9月6日
 LV7 2023年8月28日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友