一、問題
在web.xml中添加如下配置無效
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
訪問http://localhost/KingWeixin/ 無作用
二、解決問題
2.1、問題分析
1.默認tomcat容器的默認頁面。 /index.html 這種方式適合訪問靜態的頁面(也包括JSP)或者說是沒有任何參數的頁面。 2.spirng mvc 默認index controller 方式 如果在tomcat容器沒有配置默認頁面,怎spring mvc 會主動去尋找/index的controller,如果有則會調用,沒有則會顯示404頁面。 @RequestMapping(value=”/index”) public ModelAndView index(HttpServletRequest request, HttpServletResponse response){ return new ModelAndView(“index”); } 3.spirng mvc 配置根節點訪問“/”方式 這種方法比較極端,就是配置一個名為“/”的controller,就是輸入完網址之后就會調用。這種方法是前面兩種方法都沒有配置的時候。 @RequestMapping(value=”/”) public ModelAndView index(HttpServletRequest request, HttpServletResponse response){ return new ModelAndView(“index”); } 三種方法的級別高低:1>>3>>2;因為tomcat的容器級別比spring要高,以上3鍾配置都存在的情況,優先使用tomcat。因為配置了”/”的controller,所以會先匹配到相關的controller,而不會先尋找/index controller. 注意,即使web.xml沒有添加,tomcat也會自動默認去尋找在webroot目錄下面的index文件,如果要使用后面兩種方法,則要保證webroot下面沒有index相關的文件。 綜合經驗,第三種方法最方便 使用方法例如: @RequestMapping("/") public ModelAndView index(ModelAndView modelAndView, HttpServletRequest request, String openId) { return new ModelAndView("redirect:/toLogin.do"); } @RequestMapping("/toLogin.do") public ModelAndView toLogin(ModelAndView modelAndView,Model model, HttpServletRequest request) { modelAndView.setViewName("index"); return modelAndView; }
Spring MVC中默認HTML為靜態資源,所以我們可以通過設置我們靜態資源映射的index.html為項目默認訪問的頁面
2.2: Spring 設置靜態資源映射和目錄(切記index.html要放到html目錄下)
<mvc:resources mapping="/img/**" location="/img/" />
<mvc:resources mapping="/js/**" location="/js/" />
<mvc:resources mapping="/css/**" location="/css/" />
<mvc:resources mapping="/html/**" location="/html/" />
<mvc:resources mapping="/tinymce/**" location="/tinymce/" />
<mvc:resources mapping="/upload/**" location="/upload/" />
<mvc:resources mapping="/assset/**" location="/assset/" />
<mvc:resources mapping="/data/**" location="/data/" />
<mvc:resources mapping="/images/**" location="/images/" />
<mvc:resources mapping="/media/**" location="/media/" />
2.3:創建一個跳轉到index對象的Controller
/** * */ package com.king.weixin.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; /** * @author kingstudy@vip.qq.com * @version 創建時間:2018年6月13日 下午10:28:26 * @ClassName IndexController * @Description Spring MVC 跳轉到首頁 */ @Controller public class IndexController { @RequestMapping(value="/") public ModelAndView GoToIndex(HttpServletRequest request, HttpServletResponse response){ return new ModelAndView("index"); } }
2.3:測試localhost/項目名稱-配置OK