2024-02-17 03:01
login action 中验证方式:
@Clear
public void login(String username, String password) {
if (!validateCaptcha("verificationCode") && !CaptchaRender.validate(get("captchaKey"), get("verificationCode"))) {
renderJson(Ret.fail("验证码不正确,请重新输入"));
return;
}
..... 具体登录代码在此
}
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() {
}
}