Java Spring-MVC应用程序不发送CSS和JS文件。错误404

时间:2017-03-26 21:23:24

标签: java spring spring-mvc resources

问题很常见,我尝试了很多解决方案,但对我来说没有任何作用。 我在春天很新,所以我可能听不懂。

我有下一个文件结构:

Files structure of project

我的链接内页是由Thymeleaf模仿的:

<link rel="stylesheet" th:href="@{css/bootstrap.css}" type="text/css"/>

此外,html的头部还有属性。

好的,我的spring-context.xml是:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--to pick up all annotation in the package-->
    <context:component-scan base-package="langquiz"/>

    <mvc:annotation-driven />
    <mvc:resources mapping="/css/**" location="/css/"/>
</beans>

我尝试过一些带映射的操作(比如写入location =“/ templates / css /”或location =“css /”),也试过配置类中的资源处理程序。但没有任何帮助。

谢谢!

UPD: 改变了

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

<mvc:resources mapping="/css/**" location="/templates/"/>

并尝试了

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

但仍然没有结果。

3 个答案:

答案 0 :(得分:1)

您的映射不正确,其中location应包含您的templates目录,如下所示:

<mvc:resources mapping="/css/**" location="/templates/css/"/>

您可以参考春季文档中的here

  

例如,使用URL模式提供资源请求   来自网络中公共资源目录的 / resources /   您将使用的应用程序根目录:

<mvc:resources mapping="/resources/**" location="/public-resources/"/>

答案 1 :(得分:1)

使用

<mvc:resources mapping="/css/**" location="/templates/css/"/>

或添加资源处理程序

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/css/**").addResourceLocations("/templates/css/");
}

}

答案 2 :(得分:0)

更改为使其正常工作。

仍然想知道是否有办法让网站不在http://localhost:8080/project-name-snapshot上但在http://localhost:8080