Java验证码

来源:互联网 发布:淘宝小视频保存到手机 编辑:程序博客网 时间:2024/06/02 04:15

这里写图片描述

Servlet代码 (JcaptchaServlet.java)
/**
* 提供验证码图片的Servlet
*/
@SuppressWarnings(“serial”)
public class JcaptchaServlet extends HttpServlet {
public static final String CAPTCHA_IMAGE_FORMAT = “jpeg”;

private ImageCaptchaService captchaService;private SessionProvider session;@Overridepublic void init() throws ServletException {    WebApplicationContext appCtx = WebApplicationContextUtils            .getWebApplicationContext(getServletContext());    captchaService = (ImageCaptchaService) BeanFactoryUtils            .beanOfTypeIncludingAncestors(appCtx, ImageCaptchaService.class);    session = (SessionProvider) BeanFactoryUtils            .beanOfTypeIncludingAncestors(appCtx, SessionProvider.class);}@Overrideprotected void doGet(HttpServletRequest request,        HttpServletResponse response) throws ServletException, IOException {    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 = session.getSessionId(request);        BufferedImage challenge = captchaService.getImageChallengeForID(                captchaId, request.getLocale());        // Jimi.putImage("image/jpeg", challenge, jpegOutputStream);        ImageIO.write(challenge, CAPTCHA_IMAGE_FORMAT, jpegOutputStream);    } catch (IllegalArgumentException e) {        response.sendError(HttpServletResponse.SC_NOT_FOUND);        return;    } catch (CaptchaServiceException e) {        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);        return;    }    // catch (JimiException e) {    // response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);    // 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 = response.getOutputStream();    responseOutputStream.write(captchaChallengeAsJpeg);    responseOutputStream.flush();    responseOutputStream.close();}

}

这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述

导入jcaptcha-my-1.0.jar

0 0
原创粉丝点击