为什么WebMvcConfigurer覆盖方法不起作用?

时间:2019-07-30 07:42:05

标签: java spring spring-boot model-view-controller

我用Spring Boot创建了一个项目。我正在配置基本配置,但是实现WebMvcConfigurer时出现问题。

addInterceptors效果很好,但是addViewControllers和addResourceHandlers无效。没有错误,但是这两种方法都不适用。

我认为我没事,但是我找不到原因。我知道为什么吗?

[项目结构]

  

java
  --me
  ----东方之光
  ------样本
  --------控制器
  ----------SampleController.java
  ------ config
  --------RootContextConfig.java
  --------Application.java
  -------- DispatcherServletConfig.java

[RootContextConfig.java]

@Configuration
@ComponentScan(
        basePackages = {"me.eastglow.*"},
        excludeFilters = {@Filter(Controller.class)}
)
public class RootContextConfig {
}

[Application.java]

@SpringBootApplication
public class Application extends SpringBootServletInitializer {

    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    @Override
    public void onStartup(ServletContext container) throws ServletException {

        // Create the 'root' Spring application context
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(RootContextConfig.class);

        // Manage the lifecycle of the root application context
        container.addListener(new ContextLoaderListener(rootContext));

        // Create the dispatcher servlet's Spring application context
        AnnotationConfigWebApplicationContext dispatcherServlet = new AnnotationConfigWebApplicationContext();
        dispatcherServlet.register(DispatcherServletConfig.class);

        // Register and map the dispatcher servlet
        ServletRegistration.Dynamic dispatcher = container.addServlet("appServlet", new DispatcherServlet(dispatcherServlet));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("*.json");
        dispatcher.addMapping("*.do");
    }

}

[DispatcherServletConfig.java]

@Configuration
@ComponentScan(
        basePackages={"me.eastglow.*"},
        useDefaultFilters = false,
        includeFilters={@Filter(Controller.class)},
        excludeFilters={@Filter(Service.class), @Filter(Repository.class)}
)
@EnableWebMvc
@PropertySource(
        value={"classpath:application-${spring.profiles.active}.properties", "classpath:log4jdbc.log4j2.properties"},
        ignoreResourceNotFound = true)
public class DispatcherServletConfig implements WebMvcConfigurer {

    private final static String[] RESOURCE_HANDLER_PATH = {"/favicon.ico"
            , "/image/**"
            , "/js/**"};
    private final static String[] RESOURCE_HANDLER_LOCATION = {"/resources/favicon.ico"
            , "/resources/image/"
            , "/resources/js/"};

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        CacheControl cacheControl = CacheControl.empty().cachePrivate();

        registry.addResourceHandler(RESOURCE_HANDLER_PATH).addResourceLocations(RESOURCE_HANDLER_LOCATION).setCacheControl(cacheControl);
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("redirect:/member/login.do");
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new BusinessInterceptor()).addPathPatterns("/**");
    }

    @Bean
    public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager) {
        List<ViewResolver> resolvers = new ArrayList<>();

        InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
        internalResourceViewResolver.setViewClass(JstlView.class);
        internalResourceViewResolver.setPrefix("/WEB-INF/views/");
        internalResourceViewResolver.setSuffix(".jsp");
        resolvers.add(internalResourceViewResolver);

        ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
        resolver.setViewResolvers(resolvers);
        resolver.setContentNegotiationManager(manager);


        return resolver;
    }
}

[已更新]

public class DispatcherServletConfig implements WebMvcConfigurer {

    private final static String[] RESOURCE_HANDLER_PATH = {"/favicon.ico"
            , "/image/**"
            , "/js/**"};
    private final static String[] RESOURCE_HANDLER_LOCATION = {"/resources/favicon.ico"
            , "/resources/image/"
            , "/resources/js/"};

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        CacheControl cacheControl = CacheControl.empty().cachePrivate();

        registry.addResourceHandler(RESOURCE_HANDLER_PATH).addResourceLocations(RESOURCE_HANDLER_LOCATION).setCacheControl(cacheControl);
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("redirect:/member/login.do");
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new BusinessInterceptor()).addPathPatterns("/**");
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
            configurer.enable();
}

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(new FormHttpMessageConverter());
        converters.add(jacksonMessageConverter()); //Json Message Converter
        converters.add(new StringHttpMessageConverter());
        converters.add(new ResourceHttpMessageConverter()); // File Transfer Message Converter
    }

    @Bean
    public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager) {
        List<ViewResolver> resolvers = new ArrayList<>();

        InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
        internalResourceViewResolver.setViewClass(JstlView.class);
        internalResourceViewResolver.setPrefix("/WEB-INF/views/");
        internalResourceViewResolver.setSuffix(".jsp");
        internalResourceViewResolver.setOrder(2);
        resolvers.add(internalResourceViewResolver);

        JsonViewResolver jsonViewResolver = new JsonViewResolver();
        resolvers.add(jsonViewResolver);

        resolvers.add(beanNameViewResolver());

        ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
        resolver.setViewResolvers(resolvers);
        resolver.setContentNegotiationManager(manager);

        return resolver;
    }

    @Bean
    public TilesConfigurer tilesConfigurer() {
        TilesConfigurer configurer = new TilesConfigurer();

        configurer.setDefinitions(new String[]{"/WEB-INF/tiles/tiles.xml"});
        configurer.setCheckRefresh(true);

        return configurer;
    }

    @Bean
    public TilesViewResolver tilesViewResolver() {
        TilesViewResolver viewResolver = new TilesViewResolver();

        viewResolver.setOrder(1);

        return viewResolver;
    }

    class JsonViewResolver implements ViewResolver {
        @Override
        public View resolveViewName(String viewName, Locale locale) {
            MappingJackson2JsonView view = new MappingJackson2JsonView();
            view.setPrettyPrint(true);
            view.setContentType("application/json;charset=UTF-8");
            view.setDisableCaching(true);
            return view;
        }
    }

    @Bean(name="beanNameViewResolver")
    public BeanNameViewResolver beanNameViewResolver(){
        BeanNameViewResolver beanNameViewResolver = new BeanNameViewResolver();
        beanNameViewResolver.setOrder(0);
        return beanNameViewResolver;
    }

    @Bean(name="jacksonMessageConverter")
    public MappingJackson2HttpMessageConverter jacksonMessageConverter(){
        return new MappingJackson2HttpMessageConverter();
    }

    @Bean
    public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

1 个答案:

答案 0 :(得分:1)

您正在使用Spring Boot而不是使用它。

对于初学者,请删除您的onStartup类的Application方法。 Spring Boot负责所有这些工作。

接下来抛弃您的RootContextConfig

2清理您的DispatcherServletConfig

@Configuration
@PropertySource(
        value={"classpath:log4jdbc.log4j2.properties"},
        ignoreResourceNotFound = true)
public class DispatcherServletConfig implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("redirect:/member/login.do");
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new BusinessInterceptor());
    }
}

现在在您的application.properties中(或创建一个),添加以下内容

spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp

spring.resources.cache.cache-private=true

默认情况下,映射应该可以运行,否则将jsimages放在src/main/resources/staticsrc/main/resources/public中。

这就是您正确使用Spring Boot所需的全部(而不是替代方法)。