2013-10-08 126 views
3

我有一個用例,其中我的應用程序託管REST API和Web應用程序,我們只需將自定義標題添加到REST API。 REST API通過Spring Data REST啓用。通常我們可以使用Servlet Filter來實現這一點,但我們需要編寫隔離請求到REST API的邏輯並添加自定義標頭。如果Spring Data REST API允許爲其生成的所有響應添加默認標題,那將會很好。你怎麼看?不要說我懶惰:)REST API的自定義默認標題僅使用Spring Data REST

回答

4

由於Spring Data REST建立在Spring MVC之上,最簡單的方法是按照reference documentation中的描述配置自定義HandlerInterceptor

使用Spring Data REST最簡單的方法是擴展RepositoryRestMvcConfiguration並覆蓋repositoryExporterHandlerMapping,調用父方法,然後在其上調用….setInterceptors(…)

+0

感謝@Oliver_Gierke作品 – Stackee007

+3

是的,這也適用於我,但是對於新版本,'repositoryExporterHandlerMapping'方法消失了,並且嘗試以類似的方式調整'restHandlerMapping'不起作用。使用'addInterceptors'也不起作用。 @Oliver_Gierke,定義Spring Data REST存儲庫攔截器的新方法是什麼? –

+1

對於那些未來搜索這個問題的人可以參考http://stackoverflow.com/a/32952220/4283455這是一個更好的解決方案,我認爲:) –

8

爲鄉親尋找實際的實施細則..

攔截

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 
public class RepositoryConfig extends 
     RepositoryRestMvcConfiguration { 

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

     mapping.setInterceptors(new Object[] { new CustomInterceptor() }); 
     return mapping; 
    } 
} 
+1

對於那些未來搜索這個問題的人可以參考http://stackoverflow.com/ a/32952220/4283455這是一個更好的解決方案,我認爲:) –

1

最後我設法讓自定義攔截器對彈簧的數據也正在安裝-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); 
    } 

} 

我不得不重寫restHandlerMapping方法,複製粘貼它的內容,並添加一行repositoryMapping.setInterceptors添加自定義攔截器,在我的情況下UserInterceptor

有沒有更好的方法?