2011-03-25 81 views
3

我有一個控制器,提供文件(圖片,PDF文件結構等):如果我請求與文件忽略Spring MVC中接受頭

@Controller 
public class FileController { 

    @ResponseBody 
    @RequestMapping("/{filename}") 
    public Object download(@PathVariable String filename) throws Exception { 
     returns MyFile.findFile(filename); 
    } 

} 

以下Accept頭,我收到了406:

Request  
URL: http://localhost:8080/files/thmb_AA039258_204255d0.png 
Request Method:GET 
Status Code:406 Not Acceptable 
Request Headers 
Accept:*/* 

如果我請求與以下Accept頭相同的文件,我收到了200:

URL: http://localhost:8080/files/thmb_AA039258_204255d0.png 
Request Method: GET 
Status Code:200 OK 
Request Headers 
Accept: application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5 

這是我的春天MVC方面的唯一視圖解析器:

<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver" id="tilesViewResolver"> 
    <property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView"/> 
</bean> 

反正是有配置Spring MVC的忽略Accept頭?我已經看到了使用ContentNegotiatingViewResolver完成此操作的示例,但僅用於處理xml和json。

+0

這是一個非常類似的問題,但對於json:http://stackoverflow.com/questions/5315288/spring-returning-json-with-responsebody-when-the-accept-header-is-throws-htt – 2011-03-25 21:27:50

回答

3

所以這是我結束了得到它的工作代碼:我用這個鎖定到JSON響應類型

@Controller 
public class FileController { 

    @ResponseBody 
    @RequestMapping("/{filename}") 
    public void download(@PathVariable String filename, ServletResponse response) throws Exception { 
     MyFile file = MyFile.find(filename); 
     response.setContentType(file.getContentType()); 
     response.getOutputStream().write(file.getBytes()); 

    } 


} 
0

當您使用ResponseBody註釋時,我認爲這是交易的一部分,它會查看Accept頭並嘗試執行一些映射或其他操作。如果您無法弄清楚如何使用該註釋進行回覆,還有很多其他方式可以發送回覆。

0

@Configuration 
@EnableWebMvc 
public class ApplicationConfiguration extends WebMvcConfigurerAdapter { 

    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { 

     configurer.favorPathExtension(false); 
     configurer.ignoreAcceptHeader(true); 
     configurer.defaultContentType(MediaType.APPLICATION_JSON); 

    } 

} 

favorPathExtension(false)是因爲春天在默認情況下需要(至少在4.1.5中)支持基於路徑的內容協商(即如果URL以「.xml」結尾,它將嘗試返回XML等)。