如题,对接一个系统,有验证码,不支持 cookie,返回有格式标准。话不多说,上码:
import com.jfinal.captcha.Captcha; import com.jfinal.captcha.CaptchaManager; import com.jfinal.captcha.CaptchaRender; import com.jfinal.core.JFinal; import com.jfinal.kit.Base64Kit; import com.jfinal.kit.Kv; import com.jfinal.kit.LogKit; import com.jfinal.render.JsonRender; import com.jfinal.render.RenderException; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; /** * 生成Base64验证码 */ public class Base64CaptchaRender extends CaptchaRender { /** * 生成验证码 */ public void render() { Captcha captcha = createCaptcha(); CaptchaManager.me().getCaptchaCache().put(captcha); ByteArrayOutputStream sos = null; try { BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); String key = captcha.getKey(); String value = captcha.getValue(); drawGraphic(value, image); if (JFinal.me().getConstants().getDevMode()){ LogKit.debug("生成验证码: key=" + key + "\t value=" + value); } sos = new ByteArrayOutputStream(); ImageIO.write(image, "jpeg", sos); value = Base64Kit.encode(sos.toByteArray()); new JsonRender(Kv.of("code", 0).set("msg", "ok")// .set("data", Kv.of("captchaId", key).set("value", value))// ).setContext(request, response).render(); } catch (IOException e) { if (getDevMode()) { throw new RenderException(e); } } catch (Exception e) { throw new RenderException(e); } finally { if (sos != null) { try {sos.close();} catch (IOException e) { LogKit.logNothing(e);} } } } }
使用姿势:
Controller... public void captcha() { render(new Base64CaptchaRender()); } public ApiRet xxx() { Kv kv = ... String captchaId = kv.getStr("captchaId"); String verifyCode = kv.getStr("verifyCode"); boolean validate = Base64CaptchaRender.validate(captchaId, verifyCode); if (!validate) { return new ApiRet(403, "验证码不正确");//ApiRet 自定义返回的数据结构类 } ... }
OK~