Spring MVC不進入Controller,報錯404解決方案
1、檢查URL是否會被springmvc攔截
首先檢查訪問路徑URL是否正確被springmvc攔截,這個URL和web.,xml中對springmvc的配置有關。
2、檢查Controller層是否使用@Controller註解
檢查是否在Controll層使用@Controller註解來將其標註為元件;
只有使用了@Controller標註的Controller層才能被Springmvc識別.
3、檢查是否配置了<context:component-scan/>和<mvc:annotation-driven/>(springmvc.xml中)
3.1、檢查是否配置了<context:component-scan/>
1、<context:component-scan/>是用來指明讓springmvc容器去哪裡掃描@Controller註解,
只有springmvc找到了@Controller註解,springmvc才能進入Controller.
2、配置方式為:<context:component-scan base-package="com.taotao.controller" />
3.2、檢查<context:component-scan/>是否配置正確
1、Base-package後面如果寫成”com.taotao.controller.*”是錯誤的(不帶*,定位到包即可).
2、Base-package後面的路徑指的是Controller層所在的包,如圖,注意路徑一定要寫對.
3.3、檢查是否配置了<mvc:annotation-driven/>
<mvc:annotation-driven/>相當於註冊了DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter兩個bean,配置一些messageconverter。即解決了
@Controller註解的使用前提配置。配置方式為:<mvc:annotation-driven />
ps:<mvc:annotation-driven/>和<context:component-scan/>不分先後順序
4、檢查是否正確讀取Springmvc的配置檔案(web.xml中)
4.1、如果沒有配置<init-param></init-param>
那麼spring容器會自動去WEB-INF目錄下掃描一個叫SpringMVC-servlet.xml的配置檔案來載入springmvc容器.
4.2、如果如下圖配置了<init-param></init-param>
重點檢查一下是否classpath後面的路徑書寫的有錯誤.
注意:
1.只有成功讀取到springmvc的xml配置檔案,才能讓spring容器載入springmvc容器,然後才能識別@Controller註解並執行標註的Contoller層
2.<param-name></param-name>之間的contextConfigLocation是固定的
PS:
web.xml載入spring容器的xml配置檔案時,<param-name></param-name>之間的contextConfigLocation也是固定的.
5、檢查是否成功載入spring容器
如果spring容器都未成功載入,那麼肯定無法成功載入springmvc容器。
5.1、檢查spring容器的監聽是否正常啟動
- <listener>
- lt;listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
5.2、檢查是否正確讀取了spring容器的xml配置檔案
注意:再次強調,<param-name>標籤中的contextConfigLocation是固定的,書寫錯誤會報錯
希望可以幫到大家!!!