ajax访问java后台生成base64验证码并返回

ajax访问java后台生成base64验证码并返回

1.ajaxa方式返回随机验证码图片

public Map imageSign(HttpServletRequest request,
			HttpServletResponse response) {
		Map json = new HashMap();
		Map data = new HashMap();
		byte width = 85;
		byte height = 28;
		BufferedImage image = new BufferedImage(width, height, 2);
		Graphics2D g = image.createGraphics();
		g.setComposite(AlphaComposite.getInstance(3, 1.0F));
		Random random = new Random();
		g.setColor(new Color(231, 231, 231));
		g.fillRect(0, 0, width, height);
		g.setFont(new Font("Microsoft YaHei", 2, 24));
		String sRand = "";
		for (int responseOutputStream = 0; responseOutputStream < 4; ++responseOutputStream) {
			String rand = String.valueOf(random.nextInt(10));
			sRand = sRand + rand;
			g.setColor(new Color(121, 143, 96));
			g.drawString(rand, 13 * responseOutputStream + 16, 23);
		}
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		HttpSession session = request.getSession();
		session.setAttribute(CommonConstants.RAND_CODE, sRand);
		g.dispose();
		try {
			ImageIO.write(image, "png", baos);
			baos.close();
			byte[] img = baos.toByteArray();
			BASE64Encoder encoder = new BASE64Encoder();
			String png_base64 = encoder.encode(img);// 转换成base64串
			// png_base64 = png_base64.replaceAll("\n", "").replaceAll("\r",
			// "");// 删除
			data.put("image", png_base64);
			data.put("random", sRand);
			json = WebUtils.setJson(true, "ok", data);
		} catch (IOException e) {
			json = WebUtils.setJson(false, "no", null);
			logger.error("验证图片加载失败,:", e);
		}
		return json;
	}

2.response方式返回随机验证码图片

	public void genericRandomCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
	  response.setHeader("Cache-Control", "private,no-cache,no-store");
        response.setContentType("image/png");
        byte width = 85;
        byte height = 28;
        BufferedImage image = new BufferedImage(width, height, 2);
        Graphics2D g = image.createGraphics();
        g.setComposite(AlphaComposite.getInstance(3, 1.0F));
        Random random = new Random();
        g.setColor(new Color(231, 231, 231));
        g.fillRect(0, 0, width, height);
        g.setFont(new Font("Microsoft YaHei", 2, 24));
        String sRand = "";
        for(int responseOutputStream = 0; responseOutputStream < 4; ++responseOutputStream) {
            String rand = String.valueOf(random.nextInt(10));
            sRand = sRand + rand;
            g.setColor(new Color(121, 143, 96));
            g.drawString(rand, 13 * responseOutputStream + 16, 23);
        }
        ServletOutputStream var12 = response.getOutputStream();
        HttpSession session = request.getSession();
        session.setAttribute(CommonConstants.RAND_CODE, sRand);
        g.dispose();
        ImageIO.write(image, "png", var12);
        var12.close();
		
	}

你可能感兴趣的:(G工作中的问题)