2024-02-17 02:59
然后在 controller 中这么使用:
private void captcha() {
try {
String uuid = StrKit.getRandomUUID();
JsonCaptchaRender render = new JsonCaptchaRender(uuid);
Kv data = Kv.of("captchaKey", uuid);
FastByteArrayOutputStream os = new FastByteArrayOutputStream();
ImageIO.write(render.getImage(), "jpg", os);
data.set("img", Base64.encode(os.toByteArray()));
renderJson(Ret.data(data));
} catch (IOException e) {
renderJson(Ret.fail(e.getMessage()));
}
}
2024-02-17 02:54
先写一个 JsonCaptchaRender.java,代码如下:
import com.jfinal.captcha.Captcha;
import com.jfinal.captcha.CaptchaManager;
import com.jfinal.captcha.CaptchaRender;
import com.jfinal.kit.StrKit;
import java.awt.image.BufferedImage;
public class JsonCaptchaRender extends CaptchaRender {
private final String captchaKey;
private String code;
BufferedImage image;
public BufferedImage getImage() {
return image;
}
public void setImage(BufferedImage image) {
this.image = image;
}
public String getCaptchaKey() {
return captchaKey;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public JsonCaptchaRender(String captchaKey) {
if (StrKit.isBlank(captchaKey)) {
throw new StockException("验证码参数 captchaKey 不能为空");
}
this.captchaKey = captchaKey;
Captcha captcha = createCaptcha();
CaptchaManager.me().getCaptchaCache().put(captcha);
BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
String code = captcha.getValue();
this.setCode(code);
drawGraphic(code, image);
this.setImage(image);
}
/**
* 使用前端传入 captchaKey
*/
@Override
protected Captcha createCaptcha() {
return new Captcha(this.captchaKey, getRandomString(), Captcha.DEFAULT_EXPIRE_TIME);
}
/**
* 生成验证码
*/
@Override
public void render() {
}
}
2023-11-28 18:25
刚刚用 enjoy 现有指令实现了,你试一下:
public static void main(String[] args) {
String t = "#set(test=[1,2,3,4,5,6,7,8,9])" +
"#for(item : test)" +
"#if( for.index % 4 == 0 ) <div style='width:100%'>\n #end" +
"\t\t<span style='padding-right:10px'>#(item)</span>\n" +
"#if( for.count % 4 == 0 || for.last) </div>\n #end" +
"#end";
Engine.use().getTemplateByString(t).render(System.out);
}