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

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay