【问题标题】:Static content is not getting loaded in JSP page from spring boot application静态内容未从 Spring Boot 应用程序加载到 JSP 页面中
【发布时间】:2019-03-04 03:17:39
【问题描述】:

我正在创建一个 SpringBoot Web 应用程序,该应用程序同时呈现一个带有一些静态实体(如图像)的 .jsp 页面。 我已经尝试在 META_INFstatic 的每个文件夹中添加静态文件,但在控制台出现 404 错误并且图像不显示。


Here is my project structure


HTML代码如下:

<img src="image/nia-logo.png">

Spring Boot Application类如下:

@SpringBootApplication
@PropertySource("classpath:application.properties")
@EnableWebMvc
public class FeedbackApplication  implements WebMvcConfigurer{  

@Autowired
private Environment environment;


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



@Bean
public ViewResolver getViewResolver() {     
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setPrefix("/WEB-INF/jsp/");
    viewResolver.setSuffix(".jsp");
    viewResolver.setViewClass(JstlView.class);
    return viewResolver;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    if (!registry.hasMappingForPattern("/resources/**")) {
        registry.addResourceHandler("/resources/**").addResourceLocations(
                "classpath:/resources/static/");
    }

}

}


请帮助我并指出我在哪里犯了错误。

【问题讨论】:

    标签: java html spring-mvc jsp spring-boot


    【解决方案1】:

    在 addResourceHandlers 配置中,它定义了任何以/resources/** 开头的调用都被视为资源文件。

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        if (!registry.hasMappingForPattern("/resources/**")) {
            registry.addResourceHandler("/resources/**").addResourceLocations(
                "classpath:/static/");
        }
    }
    

    所以你需要做的是将src url更改为<img src="/resources/image/nia-logo.png">

    希望这会有所帮助!快乐编码:)

    【讨论】:

    • 我是这个架构的新手,我帮助我找到解决这个问题的最佳方法。
    • 更改 src url 后,您是否检查过它是否也在开发服务器上实现?如果您使用的是 chrome 或 firefox,则可以调出开发者模式以查看 src url 是否更改。
    • 我正在使用 Chrome 并在“网络”选项卡中,找不到图像 404,它选择的 URL 是:localhost:8080/resources/image/nia-logo.png
    • 好的,你应该把addResourceLocations改成"classpath:/static/"看看这是否可行!
    • 在春天classpath 指向src/main/resources,所以如果你将资源位置设置为classpath:/resources/,那么它所做的就是在src/main/resources 下找到资源文件夹,这对你来说是多余和错误的案子。您将静态文件放在src/main/resources/static 下,所以位置只是classpath:/static/ :) 顺便说一句,我会改变我的答案。
    猜你喜欢
    • 2017-07-19
    • 1970-01-01
    • 2017-03-01
    • 2017-03-25
    • 1970-01-01
    • 2017-04-05
    • 2015-05-24
    • 2014-07-04
    • 1970-01-01
    相关资源
    最近更新 更多