Spring无法加载CSS/JS资源求助(Spring MVC+Spring Security+Tomcat)
Hey there, let's work through these issues step by step—they're super common when setting up static resources in a Spring stack, so you're not alone!
1. Why You're Seeing the 404 & MIME Type Error
The "MIME type ('text/html') is not executable" message is a key clue: your server isn't finding the jquery.min.js file, so it's returning an HTML error page instead. That's why Chrome rejects it as a valid script. Let's fix the root cause first.
Check Your mvc:resources Configuration
First, confirm your Spring MVC resource mapping points to the correct location. In your spring-servlet.xml, the config should look like this:
<!-- Maps requests to /web-resources/** to your actual static files folder --> <mvc:resources mapping="/web-resources/**" location="/WEB-INF/web-resources/"/>
- Double-check the
locationmatches your project structure. If yourweb-resourcesfolder lives directly under thewebapproot (not insideWEB-INF), update the location to"/web-resources/". - Remember: Tomcat (especially on Linux systems) is case-sensitive—make sure folder and file names match exactly what's in your config.
Let Spring Security Ignore Static Resources
Spring Security blocks all requests by default, so it's probably intercepting your resource calls. Add this to your Spring Security config to whitelist your static assets:
XML Config (security.xml):
<!-- Allow unauthenticated access to all web-resources --> <security:http pattern="/web-resources/**" security="none"/>
Java Config:
@Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/web-resources/**").permitAll() // Whitelist static resources .anyRequest().authenticated(); // Your existing security rules }
Fix Resource Paths in Your Views
If your app is deployed with a context path (e.g., http://localhost:8080/my-app/), hardcoding paths like /web-resources/jquery.min.js will break. Use JSTL's <c:url> tag to generate correct URLs automatically:
<script src="<c:url value='/web-resources/jquery.min.js'/>"></script>
This ensures the URL includes your app's context path if it exists, avoiding unnecessary 404s.
2. Fixing the favicon.ico 404
Browsers automatically request /favicon.ico from your app's root. To fix this:
- Option 1: Place a
favicon.icofile directly in yourwebapproot folder. - Option 2: Add a mapping for it in your
mvc:resourcesconfig, then reference it in your HTML:<mvc:resources mapping="/favicon.ico" location="/web-resources/favicon.ico"/><link rel="icon" href="<c:url value='/favicon.ico'/>" type="image/x-icon">
Final Quick Checks
- Clear Browser Cache: Chrome might be caching old error responses. Press
Ctrl+Shift+Rto do a hard refresh and test again. - Verify File Permissions: On Linux/macOS, make sure Tomcat has read access to your
web-resourcesfolder and files (set folder permissions to755, file permissions to644).
内容的提问来源于stack exchange,提问作者Vickie Jack

