Sunday, 4 August 2019

Spring Boot: Adding interceptor to spring boot application

This is continuation to my previous post. You can download previous working application from this link.

Step 1: Create interceptor class.
PerformanceReportInterceptor.java
package com.sample.app.interceptors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class PerformanceReportInterceptor implements HandlerInterceptor {

    private long startTime;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        startTime = System.nanoTime();
        return true;

    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            @Nullable ModelAndView modelAndView) throws Exception {
        long executionTime = System.nanoTime() - startTime;
        modelAndView.addObject("executionTime", executionTime);
    }
}


Step 2: Define a configuration class that registers all the interceptors.

InterceptorConfiguration.java

package com.sample.app.configurations;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.sample.app.interceptors.PerformanceReportInterceptor;

@Configuration
public class InterceptorConfiguration implements WebMvcConfigurer{
    @Override
    public void addInterceptors(InterceptorRegistry registry){
        registry.addInterceptor(new PerformanceReportInterceptor()).addPathPatterns("/*");
    }
}


Update hello.jsp like below.

hello.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h1>
        Execution Time : ${executionTime} nanoseconds<br />
    </h1>
</body>
</html>


Total project structure looks like below.


Run App.java.

Open the url 'http://localhost:8080/hello', you can see below kind of screen.

You can download complete working application from this link.



Previous                                                    Next                                                    Home

No comments:

Post a Comment