SpringBoot实现图形验证码
在Spring Boot中实现图形验证码,你可以使用captcha
库。以下是一个简单的例子:
- 添加
captcha
依赖到你的pom.xml
中:
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
- 创建一个
CaptchaController
来生成和处理验证码:
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
@RestController
public class CaptchaController {
@Autowired
private Producer kaptchaProducer;
@GetMapping("/captcha")
public void getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setDateHeader("Expires", 0);
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
response.addHeader("Cache-Control", "post-check=0, pre-check=0");
response.setHeader("Pragma", "no-cache");
response.setContentType("image/jpeg");
String capText = kaptchaProducer.createText();
BufferedImage bi = kaptchaProducer.createImage(capText);
request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
ServletOutputStream out = response.getOutputStream();
ImageIO.write(bi, "jpg", out);
try {
out.flush();
} finally {
out.close();
}
}
}
- 配置
Producer
的属性,例如在application.properties
中:
kaptcha.border=no
kaptcha.textproducer.font.color=black
kaptcha.image.width=120
kaptcha.image.height=40
kaptcha.textproducer.char.length=4
kaptcha.textproducer.font.size=30
- 确保你的Spring Boot应用程序扫描到
@Controller
或@RestController
注解的类。
完成以上步骤后,你可以通过访问/captcha
端点来获取验证码图片。在实际的应用中,你可能需要结合前端JavaScript来自动刷新验证码或处理验证逻辑。
评论已关闭