验证码图片

开发工具与关键技术:MyEclipse 10、java
作者:梁添荣
撰写时间:2019-07-18

做登录时,不免会需要验证码。具体思路是:先随机生成几个数字或字母保存,再用BufferedImage和Graphics生成一张图片,再把生成的验证码放进图片中,
具体代码如下:
public class pictureLoginT extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request,response);
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//设置响应头
		response.setHeader("Pragma", "No-Cache");
		response.setHeader("Cache-Control", "no_cache");
		response.setDateHeader("Expries", 0);
		
		//生成验证码
		Random random=new Random();
		int size=3;
		String code="";
		char c;
		for (int i = 0; i <size; i++) {//产生验证码
			int number =random.nextInt(20);
			if(number % 2==0){//若随机数为偶数则生成一个数字
				c=(char) ('0'+(char) ((int) (Math.random()) * 10));
			}else{//否则生成一个字母
				c=(char) ((char) ((int) (Math.random() *26)) +'A');
			}
			code=code+c;
		}
		request.getSession().setAttribute("code", code);
		
		//生成验证码图片
		int width = 30*3;
		int height=30;
		BufferedImage image=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics gr=image.getGraphics();
		gr.setColor(Color.WHITE);
		gr.fillRect(0, 0, width-1, height-1);
		for (int i = 0; i < 5; i++) {//图片画干扰线
			int x1=random.nextInt(width);
			int x2=random.nextInt(width);
			int y1=random.nextInt(height);
			int y2=random.nextInt(height);
			gr.setColor(randomColor());
			gr.drawLine(x1,y1,x2,y2);
		}
		gr.setColor(randomColor());
		gr.setFont(randomFont());
		gr.drawString(code, 10, 22);
		gr.dispose();
		ImageIO.write(image, "JPEG", response.getOutputStream());
	}
	private Random r=new Random();
	private String[] fontNames={"宋体","华文楷体", "黑体", "微软雅黑", "楷体_GB2312" };
	//生成随机字体
	private Font randomFont() {
		int index=r.nextInt(fontNames.length);
		String fontName=fontNames[index];
		int style=r.nextInt(4);
		int size=r.nextInt(3)+24;
		return new Font(fontName,style,size);
	}
	//生成随机颜色
	private Color randomColor() {
		int red=r.nextInt(150);
		int green=r.nextInt(150);
		int blue=r.nextInt(150);
		return new Color(red,green,blue);
	}
}

上一篇:javax.servlet.ServletException: Servlet.init() for servlet springmvc threw exception


下一篇:java – 由HttpServlet抛出的ServletExceptions被Tomcat记录为’SEVERE’,尽管以推荐的方式处理