Spring 4中静态文件加载失败:JSP引入jQuery报404错误
Hey Lakshmi, sorry to hear you're stuck with that 404 error when loading jQuery in your JSP. Let's walk through the most common fixes based on the configuration you shared.
1. 补全视图解析器的后缀配置
First off, I notice your viewResolver.setSuffix(".... is incomplete. You'll need to finish that with .jsp so Spring can correctly locate your JSP files:
@Bean public ViewResolver viewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/WEB-INF/views/"); viewResolver.setSuffix(".jsp"); // 补全JSP后缀 return viewResolver; }
2. 添加静态资源映射(关键!)
Since you're using @EnableWebMvc, this disables Spring's default static resource handling. You need to explicitly configure where your static files (like jQuery) are stored by implementing WebMvcConfigurer and overriding addResourceHandlers:
@Configuration @EnableWebMvc @ComponentScan(basePackages = { "common.spring.controller" }) public class WebConfig implements WebMvcConfigurer { // 实现WebMvcConfigurer接口 // 你的viewResolver Bean... @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // 根据你的实际文件位置选择下面的配置: // 如果jQuery放在 webapp/static/js/ 目录下 registry.addResourceHandler("/static/**") .addResourceLocations("/static/"); // 如果jQuery放在 src/main/resources/static/js/ 目录下(Maven/Gradle项目常用) // registry.addResourceHandler("/static/**") // .addResourceLocations("classpath:/static/"); } }
3. 修正JSP中的jQuery引用路径
Make sure your JSP references jQuery using the correct path, including the context path to avoid issues with different deployment contexts:
<!-- 假设jQuery文件在 static/js/jquery.min.js --> <script src="${pageContext.request.contextPath}/static/js/jquery.min.js"></script>
Using ${pageContext.request.contextPath} ensures the path works regardless of how your app is deployed (e.g., http://localhost:8080/yourapp/ vs http://localhost:8080/).
4. 验证文件位置
Double-check that your jQuery file is actually in the directory you configured:
- If you used
/static/as the resource location, the file should be atwebapp/static/js/jquery.min.jsorsrc/main/resources/static/js/jquery.min.js - Ensure the filename is correct (case-sensitive on some servers!)—no typos like
JQuery.min.jsinstead ofjquery.min.js
Give these steps a try, and your 404 should be resolved. Let me know if you run into any other issues!
内容的提问来源于stack exchange,提问作者Lakshmi

