How to use spring MVC's tag in a java application context?

后端 未结 3 912
误落风尘
误落风尘 2020-12-05 03:35

I have created \'for now\' a simple and basic spring web application. I am used to have a deployment descriptor as a simple web.xml file, and then an application context as

3条回答
  •  死守一世寂寞
    2020-12-05 04:12

    To be able to serve static resources in Spring MVC application you need two XML-tags: and . The same in the Java-based Spring configuration will be:

    @Configuration
    @EnableWebMvc
    public class WebMvcConfig extends WebMvcConfigurerAdapter {
    
        // equivalents for  tags
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/css/**").addResourceLocations("/css/").setCachePeriod(31556926);
            registry.addResourceHandler("/img/**").addResourceLocations("/img/").setCachePeriod(31556926);
            registry.addResourceHandler("/js/**").addResourceLocations("/js/").setCachePeriod(31556926);
        }
    
        // equivalent for  tag
        @Override
        public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
            configurer.enable();
        }
    
        // ... other stuff ...
    }
    

    Note that since @EnableWebMvc annotation is used there's no need to extend directly WebMvcConfigurationSupport, and you should just extend WebMvcConfigurerAdapter. See JavaDoc for @EnableWebMvc for details.

提交回复
热议问题