2011-03-25 43 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等)。

相关问题