Spring MVC静态资源加载失败:404错误求助(附配置代码)
Hey there, let's work through your static resource problem. You mentioned your Java config seems correct but you're still hitting issues—let's break down common pitfalls and fixes based on the code snippet you shared.
First, let's clean up and complete the configuration you provided, since the configureDefaultServletHandling method was truncated:
@Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**") .addResourceLocations("/resources/") .setCachePeriod(3600) .resourceChain(true) .addResolver(new PathResourceResolver()); } // Make sure this method is fully implemented @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); }
Now let's go through key checks and fixes:
Verify your static resource directory location
If you're using a Maven/Gradle project, ensure yourresourcesfolder is undersrc/main/webapp(notsrc/main/resources—that folder is for classpath resources, not web-accessible files). If you did put static resources insrc/main/resources, update youraddResourceLocationsto use the classpath prefix:.addResourceLocations("classpath:/resources/")Fix JSP resource references
Never hardcode paths in JSPs—use the context path to avoid issues when your app is deployed to a non-root URL. Use either:- Expression language:
<link rel="stylesheet" href="${pageContext.request.contextPath}/resources/css/style.css"> - JSTL
<c:url>tag (add<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>at the top of your JSP first):<link rel="stylesheet" href="<c:url value='/resources/css/style.css'/>">
- Expression language:
Check DispatcherServlet mapping
If your DispatcherServlet is mapped to/*instead of/, it will intercept all requests—including static resources. TheconfigureDefaultServletHandling.enable()call we added tells Spring to delegate unhandled requests (like static files) to the container's default servlet, which is critical here. If you're using/as the mapping, this is less of an issue but still good to have enabled.Disable caching during development
YoursetCachePeriod(3600)caches resources for an hour, which can mask fixes during debugging. For development, set it to0to avoid browser caching old (or non-existent) resources:.setCachePeriod(0)Check for path case sensitivity
If you're deploying to a Linux-based server, file paths are case-sensitive. Make sure the paths in your JSP references match the actual file system (e.g.,/resources/Css/Style.cssvs/resources/css/style.csswill fail on Linux).
If you're still stuck, share a bit more info:
- Your project directory structure
- Exact error messages (like 404 URLs shown in browser dev tools)
- The full DispatcherServlet configuration and web.xml (if using it)
内容的提问来源于stack exchange,提问作者mx_ramos




