Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom default headers for REST API only using Spring Data REST

I have a use case where my application hosts REST API and web application and we need to add custom header to REST APIs only. REST APIs are enabled through Spring Data REST. Typically we could use Servlet Filter to achieve this but we need code the logic of isolating requests to our REST API and add the custom headers. It would be nice if Spring Data REST API allows to add a default header to all the responses it generates. What are your thoughts? Don't say I am lazy :)

like image 709
Stackee007 Avatar asked Feb 04 '26 17:02

Stackee007


1 Answers

For folks looking for actual implementation details..

Interceptor

public class CustomInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throws Exception {
        System.out.println("adding CORS headers.....");
        response.addHeader("HEADER-NAME", "HEADER-VALUE");
        return true;
    }

}

Java Configuration

@Configuration
public class RepositoryConfig extends
        RepositoryRestMvcConfiguration {

    @Override
    public RequestMappingHandlerMapping repositoryExporterHandlerMapping() {
        RequestMappingHandlerMapping mapping = super
                .repositoryExporterHandlerMapping();

        mapping.setInterceptors(new Object[] { new CustomInterceptor() });
        return mapping;
    }
}
like image 89
Stackee007 Avatar answered Feb 06 '26 13:02

Stackee007