servlet 代码:
package com.radicasys.signup.jcaptcha;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.octo.captcha.service.CaptchaServiceException;
import com.octo.captcha.service.image.ImageCaptchaService;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class ImageCaptchaServlet extends HttpServlet {
private static final long serialVersionUID = 3258417209566116145L;
private Log logger = LogFactory.getLog(this.getClass());
public void init(ServletConfig servletConfig) throws ServletException {
super.init(servletConfig);
}
protected void doGet(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) throws ServletException,
IOException {
byte[] captchaChallengeAsJpeg = null;
// the output stream to render the captcha image as jpeg into
ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
try {
// get the image captcha service defined via the
//SpringFramework
ApplicationContext ctx = WebApplicationContextUtils
.getRequiredWebApplicationContext(getServletContext());
Object bean = ctx.getBean("jcaptchaService");
ImageCaptchaService imageCaptchaService = (ImageCaptchaService) bean;
// get the id that will identify the generated captcha.
// the same id must be used to validate the response
String captchaId = httpServletRequest.getParameter("captchaId");
logger.debug("captchaIdParameter: "
+ httpServletRequest.getParameter("captchaId"));
if (captchaId == null) {
// If a captcha id is not passed in, use the session id
captchaId = httpServletRequest.getSession().getId();
logger.debug("httpServletRequest.session.id: "
+ httpServletRequest.getSession().getId());
}
logger.debug("captchaId: " + captchaId);
// call the ImageCaptchaService getChallenge method
BufferedImage challenge = imageCaptchaService
.getImageChallengeForID(captchaId,
httpServletRequest.getLocale());
// a jpeg encoder
JPEGImageEncoder jpegEncoder = JPEGCodec
.createJPEGEncoder(jpegOutputStream);
jpegEncoder.encode(challenge);
} catch (IllegalArgumentException e) {
httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
} catch (CaptchaServiceException e) {
httpServletResponse
.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
// flush it in the response
httpServletResponse.setHeader("Cache-Control", "no-store");
httpServletResponse.setHeader("Pragma", "no-cache");
httpServletResponse.setDateHeader("Expires", 0);
httpServletResponse.setContentType("image/jpeg");
ServletOutputStream responseOutputStream = httpServletResponse
.getOutputStream();
responseOutputStream.write(captchaChallengeAsJpeg);
responseOutputStream.flush();
responseOutputStream.close();
}
}
web.xml加入:
<servlet> <servlet-name>jcaptcha</servlet-name> <servlet-class> com.radicasys.signup.jcaptcha.ImageCaptchaServlet </servlet-class> <load-on-startup>3</load-on-startup> </servlet> <servlet-mapping> <servlet-name>jcaptcha</servlet-name> <url-pattern>/user/jcaptcha</url-pattern> </servlet-mapping>
jsp页面代码如下:
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<script language="javascript" type="text/javascript"> function changeImage() { document.getElementById('kaptchaImage').src = 'jcaptcha?captchaId=' + Math.random(); } </script>
<tr>
<th nowrap="nowrap"><fmt:message key="rememberPassword.code"/></th>
<td>
<s:url value="./jcaptcha" id="jcaptcha">
<s:param name="captchaId" value="captchaId"/>
</s:url>
<img src="<s:property value="#jcaptcha"/>" width="130" id="kaptchaImage"
name="photo" οnclick="changeImage();"></td>
</tr>
<tr>
<th></th>
<td><a href="javascript:changeImage();" title="<fmt:message key="user.jcaptcha.see"/>"
tabindex="-2" style="color: gray; width: 130px"><fmt:message key="user.jcaptcha.see"></fmt:message></a></td>
</tr>
<tr>
<th></th>
<td valign="top"><fmt:message key="user.validateCode"></fmt:message> <input type="text"
name="jcaptchaResponse
" value=''></td>
</tr>
<tr>
<td colspan="2"><s:submit value="%{getText('button.next')}" /></td>
</tr>
struts2 action中的代码:
private String jcaptchaResponse;
//set get method......
public boolean checkJcaptcha() {
boolean flag = false;
String id = getRequest().getSession().getId();
if (StringUtils.isNotBlank(jcaptchaResponse)) {
flag = imageCaptchaService.validateResponseForID(id,
jcaptchaResponse);
}
return flag;
}