club.zhcs.lina.web.captcha.CaptchaView Maven / Gradle / Ivy
The newest version!
package club.zhcs.lina.web.captcha;
import java.io.OutputStream;
import java.util.Map;
import javax.imageio.ImageIO;
import org.nutz.lang.random.R;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.View;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
*
* @author Kerbores([email protected])
*
*/
public class CaptchaView implements View {
ImageVerification imageVerification;
CodeCache cache;
public static final String CAPTCHA_SESSION_KEY = "CAPTCHA-SESSION-KEY-R-K-D";
Log logger = Logs.get();
public CaptchaView(CodeCache cache) {
super();
this.cache = cache;
this.imageVerification = new ImageVerification(4, new DefaultCaptchaGener());
}
public CaptchaView(CaptchaGener captchaGener, int length) {
super();
this.imageVerification = new ImageVerification(length, captchaGener);
}
public CaptchaView(CaptchaGener captchaGener) {
super();
this.imageVerification = new ImageVerification(4, captchaGener);
}
/**
* @param cache
* the cache to set
*/
public void setCache(CodeCache cache) {
this.cache = cache;
}
public CaptchaView(int length) {
super();
this.imageVerification = new ImageVerification(length, new DefaultCaptchaGener());
}
public CaptchaView(ImageVerification imageVerification) {
super();
this.imageVerification = imageVerification;
}
/*
* (non-Javadoc)
*
* @see org.springframework.web.servlet.View#getContentType()
*/
@Override
public String getContentType() {
return null;
}
/*
* (non-Javadoc)
*
* @see org.springframework.web.servlet.View#render(java.util.Map,
* javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletresponseonse)
*/
@Override
public void render(@Nullable Map model,
@NonNull HttpServletRequest request,
@NonNull HttpServletResponse response)
throws Exception {
response.setContentType("image/jpeg");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
OutputStream out = response.getOutputStream();
if (ImageIO.write(imageVerification.creatImage(), "JPEG", out)) {
logger.debug("写入输出流成功:" + imageVerification.getVerifyCode() + ".");
} else {
logger.debug("写入输出流失败:" + imageVerification.getVerifyCode() + ".");
}
String key = R.UU16();
response.addCookie(new Cookie("captcha_key", key));
cache.set(key, imageVerification.getVerifyCode());
out.flush();
out.close();
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy