DEV Community

loizenai
loizenai

Posted on

Kotlin SpringMVC HandlerInterceptor – Spring Boot

https://grokonez.com/spring-framework/spring-boot/kotlin-spring-boot/kotlin-springmvc-handlerinterceptor-spring-boot

Kotlin SpringMVC HandlerInterceptor – Spring Boot

In the tutorial, JavaSampleApproach will show you how to create a Kotlin SpringMVC HandlerInterceptor that provides a mechanism to intercept requests {preProcessing, postProcessing and afterCompletion} with SpringBoot.

I. Technologies

– Java 1.8
– Maven 3.6.1
– Spring Tool Suite – Version 3.9.0.RELEASE
– Spring Boot – 1.5.9.RELEASE
– Kotlin 1.1.61

II. Goal

We use SpringToolSuite to create a Kotlin SpringBoot project as below structure:

Kotlin SpringMVC HandlerInterceptor - project structure

Use HandlerInterceptor to intercept requests:


@Component
class LogInterceptor: HandlerInterceptor{
    
    val log = LoggerFactory.getLogger(LogInterceptor::class.java);
    
    override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, dataObject: Any) : Boolean{
        log.info("1. from PreHandle method.")
        return true
    }
    
    override fun postHandle(request: HttpServletRequest, response: HttpServletResponse, dataObject: Any, model: ModelAndView?){
        log.info("3. from PostHandle method.")
    }
    
    override fun afterCompletion(request: HttpServletRequest, response: HttpServletResponse, dataObject: Any, e: Exception?) {
        log.info("4. from AfterCompletion method - Request Completed!")
    }
}

With a simple RestAPI:


@GetMapping("/hello")
fun hello(): String{
    log.info("2. Actual Excuting - Welcome to @GetMapping: /hello!")
    return "Hello World!"
}

We make a request http://localhost:8080/hello, see logs:

More at:

https://grokonez.com/spring-framework/spring-boot/kotlin-spring-boot/kotlin-springmvc-handlerinterceptor-spring-boot

Kotlin SpringMVC HandlerInterceptor – Spring Boot

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay