问题
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 :)
回答1:
As Spring Data REST is built on top of Spring MVC, the easiest way is to configure a custom HandlerInterceptor
as described in the reference documentation.
With Spring Data REST the easiest way is to extend RepositoryRestMvcConfiguration
and override repositoryExporterHandlerMapping
, call the parent method and then invoke ….setInterceptors(…)
on it.
回答2:
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;
}
}
回答3:
Finally I managed to make the setup of custom interceptor working also on spring-data-rest 2.4.1.RELEASE.
@Configuration
public class RestMvcConfig extends RepositoryRestMvcConfiguration {
@Autowired UserInterceptor userInterceptor;
@Autowired ApplicationContext applicationContext;
@Override
public DelegatingHandlerMapping restHandlerMapping() {
RepositoryRestHandlerMapping repositoryMapping = new RepositoryRestHandlerMapping(resourceMappings(), config());
repositoryMapping.setInterceptors(new Object[] { userInterceptor }); // FIXME: not nice way of defining interceptors
repositoryMapping.setJpaHelper(jpaHelper());
repositoryMapping.setApplicationContext(applicationContext);
repositoryMapping.afterPropertiesSet();
BasePathAwareHandlerMapping basePathMapping = new BasePathAwareHandlerMapping(config());
basePathMapping.setApplicationContext(applicationContext);
basePathMapping.afterPropertiesSet();
List<HandlerMapping> mappings = new ArrayList<HandlerMapping>();
mappings.add(basePathMapping);
mappings.add(repositoryMapping);
return new DelegatingHandlerMapping(mappings);
}
}
I had to override the restHandlerMapping
method, copy-paste it's content and add a line repositoryMapping.setInterceptors
for adding custom interceptor, in my case the UserInterceptor
.
Is there any better way?
来源:https://stackoverflow.com/questions/19251846/custom-default-headers-for-rest-api-only-using-spring-data-rest