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)

Sentry mobile image

App store rankings love fast apps - mobile vitals can help you get there

Slow startup times, UI hangs, and frozen frames frustrate users—but they’re also fixable. Mobile Vitals help you measure and understand these performance issues so you can optimize your app’s speed and responsiveness. Learn how to use them to reduce friction and improve user experience.

Read full post →

👋 Kindness is contagious

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

Okay