2017-05-31 861 views
2

我使用spring來構建我的web應用程序。如何配置spring忽略無效Accept頭?

在我的自定義WebMvcConfigurationSupport類,我設置基本ContentNegotiationConfigurer類似以下內容:

@Override 
public void configureContentNegotiation(final ContentNegotiationConfigurer configurer) { 
    configurer 
      .favorPathExtension(false) 
      .favorParameter(true) 
      .parameterName("mediaType") 
      .ignoreAcceptHeader(false) 
      .useJaf(false) 
      .defaultContentType(MediaType.APPLICATION_XML) 
      .mediaType("json", MediaType.APPLICATION_JSON) 
      .mediaType("xml", MediaType.APPLICATION_XML); 
} 

我無法設置ignoreAcceptHeadertrue,因爲我的一些客戶的依賴這個頭的響應。

但是當我嘗試用無效Accept頭像Accept: :*/*訪問我的API(注意額外的冒號),彈簧重定向到/error錯誤頁面,用下面的日誌:

12:18:14.498 468443 [6061] [qtp1184831653-73] DEBUG o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver 
Resolving exception from handler [public MyController.myAction() throws java.io.IOException]: org.springframework.web.HttpMediaTypeNotAcceptableException: 
Could not parse accept header [: application/json,*/*]: Invalid mime type ": application/json": Invalid token character ':' in token ": application" 

我可以改變這個行爲?我想完全忽略Accept標題,而不是跳轉到錯誤頁面。那可能嗎?

回答

1

使用過濾器截獲錯誤標題的請求,並將它們換成(或刪除)錯誤的標題。

Adding an HTTP Header to the request in a servlet filter

在該示例中改變getHeader()方法

public String getHeader(String name) { 
    if ("accept".equals(name)) { 
     return null; //or any valid value 
    } 
    String header = super.getHeader(name); 
    return (header != null) ? header : super.getParameter(name); 
}