Implementing CAPTCHA Generation in Spring MVC
Create a new Java project and configure the basic project structure.
Add the required dependencies:
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.15.RELEASE</version>
</dependency>
</dependencies>
Implement the CAPTCHA generator controller:
package com.example.captcha.controller;
import cn.dsna.util.images.ValidateCode;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@RestController
@RequestMapping("/security")
public class CaptchaGenerator {
@GetMapping("/code/{width}/{height}/{charCount}/{lineCount}")
public void generateCaptchaImage(
@PathVariable int width,
@PathVariable int height,
@PathVariable int charCount,
@PathVariable int lineCount,
HttpServletRequest request,
HttpServletResponse response) throws IOException {
ValidateCode captcha = new ValidateCode(width, height, charCount, lineCount);
String captchaText = captcha.getCode();
request.getSession().setAttribute("captchaValue", captchaText);
captcha.write(response.getOutputStream());
}
}
Display the CAPTCHA image in the frontend:
<form>
<div>
<label>Username: <input type="text" name="username"></label>
</div>
<div>
<label>Password: <input type="password" name="password"></label>
</div>
<div>
<label>CAPTCHA: <input type="text" name="captchaInput"></label>
<img src="/security/code/60/25/4/15" alt="CAPTCHA Code">
</div>
<button type="button" onclick="submitLogin()">Login</button>
</form>
Server-side valdiation logic:
String storedCaptcha = (String) request.getSession().getAttribute("captchaValue");
if (storedCaptcha == null || storedCaptcha.trim().isEmpty()) {
return "Invalid session";
}
if (!storedCaptcha.equalsIgnoreCase(userInput.getCaptchaInput())) {
return "CAPTCHA verification failed";
}