JAVA验证码如何验证
JAVA验证码验证方法
验证码验证通常分为生成和验证两部分。以下是常见的验证码验证实现方法:
生成验证码
使用Servlet生成图片验证码:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
int width = 100;
int height = 40;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
// 生成随机验证码
String chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < 4; i++) {
int index = random.nextInt(chars.length());
sb.append(chars.charAt(index));
}
String code = sb.toString();
// 绘制验证码
g.setColor(Color.BLACK);
g.setFont(new Font("Arial", Font.BOLD, 20));
g.drawString(code, 20, 25);
// 存入session
request.getSession().setAttribute("captcha", code);
// 输出图片
response.setContentType("image/jpeg");
ImageIO.write(image, "jpeg", response.getOutputStream());
}
前端展示验证码
HTML中调用Servlet生成验证码图片:
<img src="/CaptchaServlet" onclick="this.src='/CaptchaServlet?d='+Math.random()">
<input type="text" name="captcha">
服务器端验证
在表单提交处理中验证验证码:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userCaptcha = request.getParameter("captcha");
String sessionCaptcha = (String) request.getSession().getAttribute("captcha");
if (userCaptcha == null || !userCaptcha.equalsIgnoreCase(sessionCaptcha)) {
// 验证失败处理
response.sendRedirect("error.jsp");
return;
}
// 验证成功继续业务流程
}
使用第三方库
对于更复杂的需求,可以使用Kaptcha等专门库:
-
添加Maven依赖:
<dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency> -
配置Kaptcha:
@Bean public Producer kaptchaProducer() { Properties properties = new Properties(); properties.setProperty("kaptcha.image.width", "100"); properties.setProperty("kaptcha.image.height", "40"); // 其他配置... DefaultKaptcha kaptcha = new DefaultKaptcha(); Config config = new Config(properties); kaptcha.setConfig(config); return kaptcha; }
安全注意事项
验证码实现时应注意:
- 验证码应设置有效期(通常5-10分钟)
- 验证码使用后应立即从session中移除
- 避免使用简单数学运算作为验证码
- 对验证码请求频率进行限制防止暴力破解
移动端验证码
对于短信验证码验证:

// 生成6位数字验证码
String smsCode = String.format("%06d", new Random().nextInt(999999));
// 存储到Redis并设置过期时间
redisTemplate.opsForValue().set("sms:"+phone, smsCode, 5, TimeUnit.MINUTES);
// 验证时比较用户输入和Redis中的值
以上方法涵盖了从简单图片验证码到短信验证码的常见验证场景实现方案。






