Gradle Java Web应用中CSS/JS文件放置位置及无web.xml问题咨询
Hey there! Since you're building a Java web app following Gradle's guide and aren't using a web.xml (which is totally fine with Servlet 3.0+), here's the standard, Gradle-friendly way to organize your static resources so they're accessible from JSPs and HTML files:
Core Directory Structure
Gradle's war plugin follows the Servlet specification by default, so your static assets belong under the src/main/webapp directory. This is the root of your web application's context path—everything inside here gets deployed directly to your servlet container's web root.
CSS Files
- Create a
csssubfolder insidesrc/main/webapp, so your path looks like:src/main/webapp/css/ style.css layout.css - To reference these in a JSP:
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/style.css"> - In a static HTML file (also placed under
src/main/webapp):
Pro tip: Using<link rel="stylesheet" href="/css/style.css">${pageContext.request.contextPath}in JSPs ensures your links work even if your app is deployed under a non-root context path (likehttp://localhost:8080/myapp).
JavaScript Files
- Similarly, create a
js(orjavascript) subfolder undersrc/main/webapp:src/main/webapp/js/ app.js utils.js - Reference in JSP:
<script src="${pageContext.request.contextPath}/js/app.js"></script> - Reference in static HTML:
<script src="/js/app.js"></script>
Why This Works
Servlet 3.0+ (which Gradle's web setup assumes) automatically serves static resources from the web root without needing any configuration in web.xml. Gradle's war plugin will package all contents of src/main/webapp into the root of your WAR file, so the servlet container can find and serve these files directly.
You can also add other static resource folders (like img for images) following the same pattern—just place them as direct subfolders under src/main/webapp.
内容的提问来源于stack exchange,提问作者Anil

