I am switching to use Maven for my Spring web app projects and I am running into a simple issue. I am not sure where to put the CSS and JS files in the new project structure
So if you have your DispatcherServlet configured in a REST like URL pattern such as / then css files would go under src/main/webapp/resources
Just to clarify this is what I had to do:
Make sure that in your servlet-context.xml you have as follows:
<resources mapping="/resources/**" location="/resources/" />
Create a folder if does not already exist under webapps called resources
Place your css folder along with css files there
Reference my css file as follows:
<link rel="stylesheet" href="<%=request.getContextPath()%>/resources/css/960.css"/>
I was faced with the same question in a maven project. There seems to be no good answer to my problem. So I did a simple experiment and it worked perfectly.
This is a simple maven project, I have the following directory structure: (Irrelevant directories are not shown)
───src └───main ├───java ├───resources └───webapp ├───javascript │ ├───test.js │ ├───example.js │ └───jquery-library.js ├───WEB-INF │ └───web.xml └───example.jsp
My JSP pages can refer to my javascript libraries simply as
<script src=javascript/jquery-library.js></script>
There is no need for any special configuration.
org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/appname/css/myStyles.css] in DispatcherServlet
This indicates a configuration problem with your web.xml
/spring context file. DispatcherServlet
should not be processing a request for a css
resource.
If this does not help troubleshoot the problem, you may want to post relevant snippets of your web.xml
and spring context file.
The best solution I found for this problem is to use Java Configuration
@Configuration
@EnableWebMvc
public class WebAppConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
}
From this answer, from @Mario - It depends on the packaging.
If your Maven project is WAR - put it in the webapp
directory. You can choose to use subfolders within the webapp directory ie: webapp/css/main.css
or put the file directly within the webapp directory ie: webapp/main.css
.
If you are using JAR, put in the resources
directory. As Viratoro@ mentions above, there is some configuration required to map the resources directory.