簡體   English   中英

使用@EnableWebMvc和WebMvcConfigurerAdapter進行靜態資源定位的Spring MVC配置會導致“forward:”和“redirect:”出現問題

[英]Spring MVC configuration with @EnableWebMvc and WebMvcConfigurerAdapter for static resources location causes problems with “forward:” and “redirect:”

我有一個針對Web的Spring Boot hello world和一些配置混亂:

春季版:1.2.6.RELEASE

我的項目結構:

在此輸入圖像描述

我需要提供一些靜態內容,所以我決定在某些自定義WebConfig類中重新定義此類內容的源目錄(用於學習目的):

@EnableWebMvc Javadoc說:

將此批注添加到@Configuration類可從WebMvcConfigurationSupport導入Spring MVC配置

要自定義導入的配置,請實現接口WebMvcConfigurer,或者更可能擴展空方法基類WebMvcConfigurerAdapter並覆蓋單個方法,例如:

所以下一個配置類誕生了:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/r/**").addResourceLocations("classpath:/static/r/");
        registry.addResourceHandler("/favicon.ico").addResourceLocations("classpath:/static/r/favicon.ico");
    }
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("forward:/r/diploma/index.html");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
        super.addViewControllers(registry);
    }
}

如果運行應用程序並嘗試訪問http:// localhost:8080 /我得到下一個異常:

javax.servlet.ServletException: Could not resolve view with name 'forward:/r/diploma/index.html' in servlet with name 'dispatcherServlet'

但是,如果我從WebConfig中刪除@EnableWebMvc ,我在瀏覽器中獲取了index.html。 那么這種行為的原因是什么?

實際上我有一個生產項目,我以其為例進行研究,它在WebConfig上同時具有@EnableWebMvcWebMvcConfigurerAdapter

您應該添加一個ViewResolver來解析WebConfig的視圖,如下所示:

@Bean
public InternalResourceViewResolver defaultViewResolver() {
    return new InternalResourceViewResolver();
}

當您添加@EnableWebMvc ,您將關閉所有彈簧啟動的Web自動配置,這會自動為您配置這樣的解析器。 通過刪除注釋,自動配置將再次打開,自動配置的ViewResolver可以解決問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM