Java tutorial
/* * Copyright 2010-2013 NingPai, Inc. All rights reserved. * NINGPAI PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ /** * */ package com.ningpai.common.util; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import javax.imageio.ImageIO; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.octo.captcha.service.CaptchaServiceException; import com.octo.captcha.service.multitype.MultiTypeCaptchaService; /** * ??? * * @author zhangcy * */ @Controller public class CaptchaController { public static final String CAPTCHA_IMAGE_FORMAT = "jpeg"; @Autowired private MultiTypeCaptchaService captchaService; @RequestMapping("/captcha") public void writeCaptcha(HttpServletRequest request, HttpServletResponse response) { byte[] captchaChallengeAsJpeg = null; // the output stream to render the captcha image as jpeg into ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream(); try { // get the session id that will identify the generated captcha. // the same id must be used to validate the response, the session id is a good candidate! String captchaId = request.getSession().getId(); BufferedImage challenge = captchaService.getImageChallengeForID(captchaId, request.getLocale()); try { ImageIO.write(challenge, CAPTCHA_IMAGE_FORMAT, jpegOutputStream); } catch (IOException e) { } } catch (IllegalArgumentException e) { try { response.sendError(HttpServletResponse.SC_NOT_FOUND); } catch (IOException e1) { } return; } catch (CaptchaServiceException e) { try { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } catch (IOException e1) { } return; } captchaChallengeAsJpeg = jpegOutputStream.toByteArray(); // flush it in the response response.setHeader("Cache-Control", "no-store"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/" + CAPTCHA_IMAGE_FORMAT); ServletOutputStream responseOutputStream; try { responseOutputStream = response.getOutputStream(); responseOutputStream.write(captchaChallengeAsJpeg); responseOutputStream.flush(); responseOutputStream.close(); } catch (IOException e) { } } /** * AjaxloginName? */ public boolean validateCaptcha(String captcha, String sessionID) { // If the captcha field is already rejected Boolean validCaptcha = false; if (StringUtils.isBlank(captcha)) { return validCaptcha; } try { validCaptcha = captchaService.validateResponseForID(sessionID, captcha); } catch (CaptchaServiceException e) { } return validCaptcha; } }