Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing CAPTCHA Generation in Spring MVC

Tech May 18 2

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";
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.