【问题标题】:META-INF/resources not works properly with @EnableWebMVC in Spring BootMETA-INF/resources 在 Spring Boot 中不能与 @EnableWebMVC 一起正常工作
【发布时间】:2013-10-19 01:33:43
【问题描述】:

1.

我正在使用 Spring Boot。我的主课很简单

@ComponentScan
@EnableAutoConfiguration
@Configuration
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

#2。现在我想将我的静态内容外部化到一个 jar 文件中。所以,下面是jar项目

/pom.xml
/src/main/resources/META-INF/resources/hello.json // here is my resource

我做maven install并将依赖项放入主应用程序,正常运行应用程序。现在我可以调用 http://localhost:8080/hello.json 来获取我的 hello.json 文件

#3。然后,下一步是为我的主要 Web 项目使用 Apache Tiles,因此我创建了一个 @EnableWebMvc 类来配置 tilesViewResolver

@Configuration
@EnableWebMvc
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
    public @Bean TilesViewResolver tilesViewResolver() {
        return new TilesViewResolver();
    }

    public @Bean TilesConfigurer tilesConfigurer() {
        TilesConfigurer ret = new TilesConfigurer();
        ret.setDefinitions(new String[] { "classpath:tiles.xml" });
        return ret;
    }
}

然后我再次启动应用程序并尝试hello.json 以确保一切正常。但是,出现了 404 页面。删除WebMvcConfiguration 还给我的hello.json

我应该做哪些配置来解决这个问题?

非常感谢。

【问题讨论】:

    标签: spring spring-mvc spring-boot


    【解决方案1】:

    在 Spring MVC 中,使用 XML 配置,你必须有一个像下面这样的标签来服务静态内容:

    <mvc:resources mapping="/js/**" location="/js/"/>
    

    这暗示 Spring Boot 正在做一些事情来自动猜测您有静态内容并在 META-INF/resources 中正确设置上述示例。这并不是真正的“魔法”,而是他们有一个使用 @EnableWebMvc 的默认 Java 配置,该配置具有一些非常可靠的默认值。

    当您提供自己的@EnableWebMvc 时,我猜您是在改写他们的“默认”。为了重新添加资源处理程序,您可以执行以下操作:

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/js/**").addResourceLocations("/js/").setCachePeriod(31556926);
    }
    

    这相当于上面的 XML。

    【讨论】:

    • 正确,我认为。只需删除 @EnableWebMvc 即可重新打开引导功能。顺便说一句:JSP 支持目前很差,所以 Tiles 可能不是初学者。考虑使用 Thymeleaf,或者等待 JSP 迎头赶上。
    • 我遇到了同样的问题。通过查看代码,默认位置是 "classpath:/META-INF/resources/"、"classpath:/resources/"、"classpath:/static/"、"classpath:/public/" 。我在 src/main/resources/static/image.jpg 中放了一张图片,构建并运行了我的项目,并且能够在 localhost:8080/image.jpg 访问该图片
    猜你喜欢
    • 2017-11-25
    • 1970-01-01
    • 2020-11-03
    • 2017-05-26
    • 2013-02-25
    • 1970-01-01
    • 2017-02-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多