我正在尝试创建一个示例 Spring MVC 项目,但静态文件未加载。我收到下面提到的错误。
http://localhost:8080/BPMEI/static/css/bootstrap.css无法加载资源:服务器响应状态为 404(未找到)
如果有人能帮我解决这个问题,我将不胜感激。
配置代码
package com.dgsl.bpm.configuration;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.dgsl.bpm")
public class WebConfiguration extends WebMvcConfigurerAdapter {
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("/");
}
}
初始化代码
package com.dgsl.bpm.configuration;
public class WebInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebConfiguration.class);
ctx.setServletContext(container);
ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(ctx));
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
}
}
JSP代码
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Student Enrollment Form</title>
<link href="<c:url value='/static/css/bootstrap.css' />" rel="stylesheet"></link>
</head>
<body>
最佳答案
致F2:如果你让它自己下载而不是我下载css文件并告诉Spring它们在哪里,你必须让js文件或其他东西发布到不受你自己控制的网络上。楼主的目的是如何在Spring MVC项目中加载静态文件。我认为问题出在addResourceLocations
的代码上,应该是addResourceLocations("classpath:/static/");
关于java - Spring4无法加载静态文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41457771/