I've checked around for this problem, but after 4 hours of trying many things, nothing worked for me.
I get a 405 error when trying to access my css file. Here are my Config.java
package com.myapp.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
@Configuration
@ComponentScan("com.myapp")
@EnableWebMvc
@EnableTransactionManagement
public class Config extends WebMvcConfigurerAdapter {
@Bean
public UrlBasedViewResolver setupViewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/","/css/","/js/");
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
and directories structure:
META-INF
WEB-INF
resources
|-css
| |-myapp.css
|-js
|-myapp.js
Using netbeans as IDE. I've also try to out the resources directory in WEB-INF. Same results.
Edit: my default controller below
@RequestMapping(value = "/", method = RequestMethod.GET)
public String index(ModelMap map) {
map.put("msg", "Hello Spring 4 Web MVC!");
return "index";
}
Edit 2: here is my WebinItalizer
public class WebInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(Config.class);
ctx.setServletContext(servletContext);
Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
}
}
in this initializer, if I use "/" for servlet.addMapping("/") I can not have access to the css. But if I change it to something else like servlet.addMapping("/app") I can have access to the css. But the problem if I do this is all my url will start by app/ not very cool :/