破解idea子模組使用springboot出現404問題
現象
訪問頁面出現如下錯誤,就是傳說中的白頁錯誤,程式碼404
Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback. Wed Apr 10 10:00:44 CST 2019 There was an unexpected error (type=Not Found, status=404). /WEB-INF/views/index.jsp

image.png
問題背景
環境
- 開發工具idea
- 使用Springboot
專案結構
使用了idea的模組概念,該示例的程式碼啟動類位於模組下,不是專案下。

image.png
問題分析
-
通過除錯跟蹤發現在啟動階段關鍵所在
springboot會呼叫org.springframework.boot.web.servlet.server.DocumentRoot 類的方法getCommonDocumentRoot()
private File getCommonDocumentRoot() { for (String commonDocRoot : COMMON_DOC_ROOTS) { File root = new File(commonDocRoot); if (root.exists() && root.isDirectory()) { return root.getAbsoluteFile(); } } return null; }
-
在該方法中增加斷點,可以看到這裡顯示的相對路徑
image.png
-
我們使用右鍵調出計算表示式的視窗
image.png
-
根據root我們去獲得絕對路徑,發現問題所在
image.png
-
springboot按照專案路徑去查詢我們專案資源,而不是按照模組的根路徑去查詢的,所以導致找不到對應頁面,然後就出現了404
問題解決
既然找到了問題所在,我們就需要解決這個路徑問題,我們需要告訴idea在啟動的時候以當前模組作為根路徑,而不是以專案作為根路徑,那麼怎麼做呢?
-
開啟執行配置視窗
image.png
-
編輯working diretory,選擇
$MODULE_WORKING_DIR$

image.png
-
儲存後即可,這樣就修改了程式的相對路徑。再次執行程式後頁面可以正常訪問了。
image.png