There are many verification code applications, multiple of which are used to prevent malicious and uninterrupted entry by users.
The following describes a Java verification code method: Taking the logon function as an example (struts2 + spring2.6.5 is used in this example)
First, login. jsp writes an IMG label and js method.
/login/createJcaptcha.action" width="100" height="30" align="top" onclick="onImageClick(this);">
function onImageClick(o){ document.getElementById('captchaImage').src ='<%=request.getContextPath()%>/login/createJcaptcha.action?captchaId=' + Math.random(); }
Spring configuration file:
<bean id="captchaEngine"class="com.octo.captcha.engine.image.gimpy.SimpleListImageCaptchaEngine" /><bean id="captchaService"class="com.octo.captcha.service.image.DefaultManageableImageCaptchaService"><property name="captchaEngine" ref="gmailEngine" /><property name="minGuarantedStorageDelayInSeconds" value="600" /></bean>
Jar package: jcaptcha-2.0-alpha-1-SNAPSHOT.jar required
Background action code:
Private imagecaptchaservice captchaservice; (injected)
Create Verification Code
public void createJcaptcha() throws IOException {
byte[] captchaChallengeAsJpeg = null; ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream(); String captchaId = request.getParameter("captchaId"); if (logger.isDebugEnabled()) { logger.debug("captchaIdParameter: " + captchaId); } captchaId = request.getSession().getId(); BufferedImage challenge = getCaptchaService().getImageChallengeForID(captchaId, request.getLocale()); JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(jpegOutputStream); jpegEncoder.encode(challenge); captchaChallengeAsJpeg = jpegOutputStream.toByteArray(); response.setHeader("Cache-Control", "no-store"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/jpeg"); OutputStream os = response.getOutputStream(); try { os.write(captchaChallengeAsJpeg); os.flush(); } finally { os.close(); } }
Verification Code upon submission:
public boolean checkJcaptcha() {
Boolean flag = false; string checkcode = checkcode. trim (); // extract the verification code string id = request. getsession (). GETID (); If (stringutils. isnotblank (checkcode) {flag = This. getcaptchaservice (). validateresponseforid (ID, checkcode);} return flag ;}