【问题标题】:Ignore Accept header in spring mvc忽略spring mvc中的Accept标头
【发布时间】:2011-03-25 20:27:07
【问题描述】:

我有一个提供文件(图像、pdf 等)的控制器:

@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

这是我的 spring-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。

【问题讨论】:

标签: java spring spring-mvc


【解决方案1】:

所以这是我最终让它工作的代码:

@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());

    }


}

【讨论】:

    【解决方案2】:

    我用它来锁定 JSON 响应类型:

    @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 中)Spring 支持基于路径的内容协商(即如果 URL 以“.xml”结尾,它将尝试返回 XML 等)。

    【讨论】:

      【解决方案3】:

      当您使用 ResponseBody 注释时,我认为这是交易的一部分,它查看 Accept 标头并尝试进行一些映射或其他操作。如果您不知道如何使用该注释来发送响应,还有很多其他方法可以发送响应。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-10-31
        • 1970-01-01
        • 2012-08-15
        • 1970-01-01
        • 2010-12-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多