Spring Web Controller 在 .html 扩展名下返回 XML

标签 spring spring-mvc tomcat

我正在编写一个 Controller 来替换提供 xml 文档的遗留系统 - 但 url 有一个 .html 扩展名

我的 Controller 看起来像这样

@RequestMapping(value="/{name}.html",
                method = RequestMethod.GET,
                consumes = MediaType.ALL_VALUE,
                produces = MediaType.APPLICATION_XML_VALUE)
public @ResponseBody XmlContent getContent(@PathVariable(value = "name") String name) {
    return service.getXmlContent();
}

当我尝试点击 URL 时,出现 406 错误:

The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers.

如果我将请求映射更改为 .xml,一切正常。是否有我需要禁用的组件 - 拦截请求的 .html 部分并拒绝将其映射到 xml 的组件?

最佳答案

我找到了一个类似的 question/answer使用 spring xml 配置。对于基于注解的配置,你只需要添加这个配置类

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.favorPathExtension(false);
    }
}

关于Spring Web Controller 在 .html 扩展名下返回 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45879116/

相关文章:

java - ApplicationContext 和 ServletContext

java - 从 spring ReloadableResourceBundleMessageSource 获取所有键

angularjs - 使用 grunt 和 tomcat 的单页应用程序

java - Spring @PropertySource 从错误的 @Configuration 文件加载

java - Drools Spring 与 Jasper Report 导致 CompilationResult 冲突

java - 如何仅在使用spring单击java中的提交按钮后才转到下一页

java - 无法加载 [java.lang.Math]

java - Spring mvc 向其他包隐藏一个包

java - Spring Boot 无法解析 View

java - 使用 Capistrano 滚动部署 Java/Tomcat 应用程序