我正在使用Spring应用程序。我在访问CSS、JS和图像文件等静态资源时遇到了问题。
当我没有任何@Controller classes时,静态资源请求将由SimpleUrlHandlerMapping成功处理。
但是,在用@Controller标记类之后,静态资源URs仅指向该类中的方法(通过RequestMappingHandlerMapping)。
我是不是漏掉了什么配置?我的控制器类如下,
@Controller
public class LoginController {
@RequestMapping(name="/", method = RequestMethod.GET)
public String home() {
return "index";
}
@RequestMapping(name="login", method = RequestMethod.POST)
public String login() {
return "home";
}在我的.HTML文件中,我引用静态资源如下所示,
<link rel="stylesheet" type="text/css"
href="bootstrap/css/bootstrap.css"
th:href="@{bootstrap/css/bootstrap.css}">
<script src="bootstrap/js/bootstrap.js"
th:src="@{bootstrap/js/bootstrap.js}"></script>
<script src="jquery/jquery-3.4.1.min.js"
th:src="@{jquery/jquery-3.4.1.min.js}"></script>目录结构如下,在这里输入图像描述
我也试图像下面这样添加资源,
@Configuration
public class XbrlWebApp implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
}但这也行不通。当使用url类访问静态资源时,
http://localhost:8080/{contextpath}/bootstrap/css/bootstrap.css
它返回相同的html页面内容,而不是css文件。
发布于 2019-06-18 11:03:14
完全是我的错。在@RequestMapping方法中,
@RequestMapping(name="/", method = RequestMethod.GET)
public String home() {
return "index";
}我用了"name“属性。它应该是“价值”。由于没有找到"value“属性,所以无论出现什么GET http请求,都会将所有内容重定向到同一个方法,并返回index.html页面。所以静态资源也是一样的。弹簧配置工作良好。
发布于 2019-06-17 05:56:43
如果您使用的是JAR打包,您不需要配置任何东西,因为当您将所有内容放置在静态folder.Like --将js文件放在:resources/static/js下和resources/static/css下的css文件下时,springboot会自动配置处理静态内容的内容,并且默认的实现应该使用它。您可以使用以下链接引用它:
<link rel="stylesheet" type="text/css"
href="css/bootstrap.css"
th:href="@{bootstrap/css/bootstrap.css}">
<script src="js/bootstrap.js"
th:src="@{bootstrap/js/bootstrap.js}"></script>如果您使用WAR打包,请尝试以下配置,用于您的目录结构:
@Configuration
public class XbrlWebApp implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**")
.addResourceLocations("/resources/","classpath:/other-resources/","classpath:/static/");
}在html中使用:
<link rel="stylesheet" type="text/css"
href="resources/static/bootstrap/css/bootstrap.css"
th:href="@{bootstrap/css/bootstrap.css}">
<script src="resources/static/bootstrap/js/bootstrap.js"
th:src="@{bootstrap/js/bootstrap.js}"></script>
<script src="jquery/jquery-3.4.1.min.js"
th:src="@{jquery/jquery-3.4.1.min.js}"></script>如果要创建WAR,则所有资源实际上都将复制到webapps/resources文件夹,同时保留文件夹structure.So尝试上述配置。
https://stackoverflow.com/questions/56620313
复制相似问题