【发布时间】:2017-05-18 09:17:20
【问题描述】:
我正在尝试创建一个示例 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>
【问题讨论】:
-
你的jsp文件在哪里?在
WEB-INF或WEB-INF/{some_other_folder}中? -
JSP 文件位于 'WEB-INF\views\welcome.jsp'
-
你可以试试
<c:url value='../../static/css/bootstrap.css' /> -
我进行了更改,但仍然无法正常工作,但错误已更改,如下所述 'localhost/:10 GET localhost:8080/static/css/bootstrap.css'
-
跟着我的回答老兄。