SpringBoot基礎學習(番外9.1)Spring MVC或Spring Boot配置預設訪問頁面不生效?
1、tomcat配置預設訪問頁面
進入 tomcat 的 conf 目錄,編輯 web.xml 檔案。在 <web-app></web-app> 新增預設訪問頁面。
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
首先預設訪問index.html頁面,如果該頁面不存在,則會訪問index.jsp,以此類推。這種方式適合訪問靜態的頁面(也包括JSP)或者說是沒有任何引數的頁面。
2、Spring Boot設定index預設頁面
新建一個類,繼承WebMvcConfigurerAdapter類,並加上@Configuration,此方式在tomcat沒有配置預設訪問頁面的情況下生效。
@Configuration public class DefalutPage extends WebMvcConfigurerAdapter { @Override public void addViewControllers( ViewControllerRegistry registry ) { registry.addViewController( "/" ).setViewName( "forward:/index.html" ); registry.setOrder( Ordered.HIGHEST_PRECEDENCE ); super.addViewControllers( registry ); } }
注:在Spring Boot 2.0版本之後編輯器提示已過時,實現WebMvcConfigurer介面即可。
3、配置根節點訪問“/”方式
在 Controller 配置一個名為 "/" 的訪問路徑。當輸入完網址後就會呼叫。此方式在前面三種都沒有配置的情況才會呼叫。
@RequestMapping(value="/")
public String index(){
return "index";
}
}
4、Controller 配置index預設頁面
如果tomcat和Spring Boot沒有配置預設訪問頁面,Spring 會主動去尋找 Controller 的 index。如果有則會呼叫,否則會報404錯誤。
@RequestMapping(value="/index")
public String index(){
return "index";
}
優先順序:1 > 2 > 3 > 4。因為tomcat的優先順序比Spring高,相應於是最高的。以上的配置,都會先去tomcat是否配置預設訪問頁面。第2種方式由於設定了HIGHEST_PRECEDENCE,除了tomcat的配置給的許可權是最高的,所以比3、4兩種優先順序高。第3種因為Controller配置了"/",會優先匹配,而不是尋找/index的Controller。
注:如果專案的web.xml沒有配置設定訪問頁面,tomcat也會自動去尋找WebRoot目錄下的index檔案。如果要使後面三種方式生效,需保證tomcat沒有配置設定訪問頁面或WebRoot目錄下沒有index檔案。
遇到問題:使用了第2種Spring Boot設定預設訪問方式,由於是使用外部的tomcat,並且tomcat配置了幾個預設訪問頁面。當時對設定預設訪問的優先順序沒有系統的瞭解,導致花費了大半天才弄明白。
白茶清歡無別事,我在等風也等你,苦酒折柳今相離,無風無月也無你。