基于struts2的一个验证码的实现

相信大家一定都知道验证码的重要性,所以对验证码不做过多介绍。以下是用struts2实现的一个验证码生成程序。

public class CheckCode extends ActionSupport {

	private static final long serialVersionUID = 1L;
	private static int WIDTH=60;
	private static int HEIGHT=20;
	public void makeImage() throws IOException{
		HttpServletRequest request = ServletActionContext.getRequest ();
		HttpSession session=request.getSession();
		HttpServletResponse response=ServletActionContext.getResponse();
		response.setContentType("image/jpeg");
		ServletOutputStream sos=response.getOutputStream();
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		
		BufferedImage image=new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
		Graphics g=image.getGraphics();
		char[] rands=generateCheckCode();
		drawBackground(g);
		drawRands(g,rands);
		g.dispose();
		
		ByteArrayOutputStream bos=new ByteArrayOutputStream();
		ImageIO.write(image, "JPEG", bos);
		byte[] buf=bos.toByteArray();
		response.setContentLength(buf.length);
		sos.write(buf);
		sos.flush();
		bos.close();
		sos.close();
		
		session.setAttribute("check_code", new String(rands));
	}
	
	private void drawRands(Graphics g, char[] rands) {
		g.setColor(Color.black);
		g.setFont(new Font(null,Font.ITALIC|Font.BOLD,18));
		g.drawString(""+rands[0], 1, 17);
		g.drawString(""+rands[1], 16, 15);
		g.drawString(""+rands[2], 31, 18);
		g.drawString(""+rands[3], 46, 16);
		
	}
	private void drawBackground(Graphics g) {
		g.setColor(Color.WHITE);
		g.fillRect(0, 0, WIDTH, HEIGHT);
		for(int i=0;i<120;i++){
			int x=(int)(Math.random()*WIDTH);
			int y=(int)(Math.random()*HEIGHT);
			int green=(int)(Math.random()*255);
			int red=(int)(Math.random()*255);
			int blue=(int)(Math.random()*255);
			g.setColor(new Color(red,green,blue));
			g.drawOval(x, y, 1,0);
			
		}
		
	}
	private char[] generateCheckCode() {
		
		String chars="0123456789abcdefghijklmnopqrstuvwxyz";
		char[] rands=new char[4];
		for(int i=0;i<4;i++){
			int rand=(int)(Math.random()*36);
			rands[i]=chars.charAt(rand);			
		}
		return rands;
	}
	

代码比较简单,不做过多赘述。需要说明的是如何在struts.xml里面对这个类进行配置。如下所示:

 <action name="image" class="com.shrx.action.Image" method="makeImage"></action>

 这里就不需要对result进行配置了,但是要对method进行配置。

最终生成的验证码如下图所示:

 

 

猜你喜欢

转载自zhaoxin1943.iteye.com/blog/1039398