如何将RequestMappingHandlerMapping和ResourceHandlers添加到springMVC配置类

时间:2015-05-22 17:18:05

标签: java spring-mvc

我有一个像这样的spring MVC配置类:

@Configuration 
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter{
@Bean
public InternalResourceViewResolver configureInternalResourceViewResolver()   {
    InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    resolver.setPrefix("/WEB-INF/views/");
    resolver.setSuffix(".jsp");
    return resolver;
}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/**").addResourceLocations(
            "/resources/");
}


}

我遇到了使用尾部斜杠管理网址的问题,类似于this。所以我想添加RequestMappingHandlerMapping类,但根据我得到的there指令,我需要扩展 WebMvcConfigurationSupport类并实现requestMappingHandlerMapping()方法,但不幸的是,我已经为资源的映射扩展了WebMvcConfigurationSupport类。有什么方法可以为我的班级添加requiest映射处理程序吗?

注意:我使用的是Spring 3.1.1.RELEASE

3 个答案:

答案 0 :(得分:6)

我没有从你的问题中得出为什么你不能使用WebMvcConfigurationSupport。如果通过你提到的“......不幸的是我已经为资源的映射扩展了WebMvcConfigurationSupport类...”你宁愿意味着你已经扩展了WebMvcConfigurerAdapter,你应该知道WebMvcConfigurationSupport暴露了完全相同的方法。

无论如何,以下应该是Spring MVC 3.1版本的工作java配置

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurationSupport {

    @Override
    @Bean
    public RequestMappingHandlerMapping requestMappingHandlerMapping() {
        RequestMappingHandlerMapping hm = super.requestMappingHandlerMapping();
        hm.setUseSuffixPatternMatch(false);
        return hm;
    }

    @Bean
    public InternalResourceViewResolver configureInternalResourceViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations(
                "/resources/");
    }
}

答案 1 :(得分:4)

使用WebMvcConfigurationSupport覆盖requestMappingHandlerMapping,可能会关闭spring boot的默认配置。更好的方法是使用WebMvcRegistrations,

@Configuration
static class CustomRequestMappingHandlerMapping {

    @Bean
    public WebMvcRegistrationsAdapter webMvcRegistrationsHandlerMapping() {
        return new WebMvcRegistrationsAdapter() {
            @Override
            public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
                return new MyRequestMappingHandlerMapping();
            }
        };
    }
}

答案 2 :(得分:1)

从Spring Boot 2.0.0开始,您可以直接使用WebMvcRegistrations

@Configuration
public class WebMvcConfig  {
    @Bean
    public WebMvcRegistrations webMvcRegistrationsHandlerMapping() {
        return new WebMvcRegistrations() {
            @Override
            public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
                return new CustomRequestMappingHandlerMapping();
            }
        };
    }
}