Java生成验证码

struts.xml配置

 

<package name="example" namespace="/" extends="struts-default">
        
        <action name="validatecode" class="ValidateCodeAction">
        <result type="stream">  
               <param name="contentType">image/jpeg</param>  
               <param name="inputName">inputStream</param>  
            </result>  
        </action>
    </package>

 

Java代码

 

public class ValidateCodeAction {
	private ByteArrayInputStream inputStream;

	public ByteArrayInputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(ByteArrayInputStream inputStream) {
		this.inputStream = inputStream;
	}

	public String execute() {
		try {
			this.setInputStream(generateImage());
		} catch (IOException e) {
			e.printStackTrace();
		}

		return "success";
	}

	/*
	 * 画验证码
	 */
	private ByteArrayInputStream generateImage() throws IOException {

		BufferedImage image = new BufferedImage(100, 20,
				BufferedImage.TYPE_INT_RGB);
		Graphics g = image.getGraphics();
		g.setColor(Color.WHITE);
		g.fillRect(0, 0, 100, 20);
		drawbg(g);
		drawValidateCode(g);
		ByteArrayInputStream input = null;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ImageIO.write(image, "JPEG", bos);
		byte[] buf = bos.toByteArray();
		input = new ByteArrayInputStream(buf);
		return input;
	}

	private void drawbg(Graphics g) {

		Random rand = new Random();
		int randx;
		int randy;
		for (int i = 0; i < rand.nextInt(100) + 500; i++) {
			g.setColor(new Color(rand.nextInt(255), rand.nextInt(255), rand
					.nextInt(255)));
			randx = rand.nextInt(100);
			randy = rand.nextInt(20);
			g.drawLine(randx, randy, randx, randy);
		}
	}
	 
	private void drawValidateCode(Graphics g) {

		String code = generateCode();
		Random rand = new Random();
		int x = 0;
		Font font = new Font("Times New Roman", Font.PLAIN, 18);
		g.setFont(font);
		for (int i = 0; i < code.length(); i++) {
			int y = 20 - rand.nextInt(4);
			g.setColor(new Color(rand.nextInt(150), rand.nextInt(150), rand
					.nextInt(150)));
			g.drawString(code.substring(i, i + 1), x, y);
			x += 20;
		}
	}

	/*
	 * 生成验证码
	 */
	private String generateCode() {

		Random rand = new Random();
		StringBuffer sbr = new StringBuffer(
				"ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789");
		int codeLen = 5;
		StringBuffer codeSbr = new StringBuffer();
		for (int i = 0; i < codeLen; i++) {
			int select = rand.nextInt(sbr.length());
			codeSbr.append(sbr.charAt(select));
			sbr.deleteCharAt(select);
		}
		ServletActionContext.getRequest().getSession().setAttribute(
				"ValidateCode", codeSbr.toString());
		System.out.println(codeSbr.toString());
		return codeSbr.toString();
	}
}

你可能感兴趣的:(java,xml,struts)