In Spring MVC (Pure Annotations, no web.xml), I wish to configure, such that, in addition to using controllers to handle dynamic data, my web app can show static html, javascript, css, and images.
I am using a Maven project structure, so I keep my web source in main/webapp/
:
main/
|-> webapp/
|-> js/
|-> something.js
|-> images/
|-> image.jpg
|-> test.html
I currently access my dynamic resources at http://localhost:8080/app-name/**
I have done a lot of research, and tried a few things, but none of them seem to work. The existing examples that I have found seem to leave out crucial pieces of information. For example, they will explain some method of configuration, but then not explain what the folder structure has to be for it to work.
An acceptable answer will explain:
- What configuration steps are necessary
- What changes, if any, must be made to my directory structure (and why they are necessary)
- What the url path will be to these static resources, based on what I have provided, above
here is my existing configuration code.
WebConfig.java:
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@Configuration
@EnableWebMvc
public class WebConfig {
}
MyWebAppInitializer.java:
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class MyWebAppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
WebApplicationContext context = getContext();
servletContext.addListener(new ContextLoaderListener(context));
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", new DispatcherServlet(context));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");
}
private AnnotationConfigWebApplicationContext getContext() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setConfigLocation("com.example.appname.config");
return context;
}
}