Maven 搭建 Spring MVC 專案,Tomcat 啟動正常,訪問 https://localhost:8080/MavenDemo/index.do 卻報 404,日誌顯示:No handler mapping found for [/index.do]。
@RequestMapping 路徑配置錯誤原代碼:
@Controller
@RequestMapping("/")
public class UserController {
@RequestMapping("index")
public String index() { return "index"; }
}
這樣配置下,實際映射路徑變為 //index(雙斜線),且無法區分不同 Action。DispatcherServlet 找不到 /index.do 對應的處理器。
@Controller
@RequestMapping("/user") // 模塊前綴,避免衝突
public class UserController {
@RequestMapping("/index.do") // 精確匹配 .do 後綴
public String index() { return "index"; }
}
DispatcherServlet 的 url-pattern 為 *.do,contextConfigLocation 指向 spring-mvc.xml。<mvc:annotation-driven/>,component-scan 掃描 Controller 包(com.tarena.controller)。InternalResourceViewResolver 前綴 /WEB-INF/jsp/,後綴 .jsp。index.jsp 放在 /WEB-INF/jsp/index.jsp。@RequestMapping(value="/index", method=RequestMethod.GET) 明確限定 HTTP 方法。@GetMapping("/index")(Spring 4.3+)。修正路徑映射並確保掃描配置正確後,請求即可順利進入 Controller。