SpringMVC 3+ 全面支援註解驅動開發,徹底擺脫繁瑣 XML 映射配置。本文演示零 XML Controller 映射,核心組件:`DispatcherServlet`、`
src/
├─ main/
│ ├─ java/
│ │ └─ com/zhy/controllers/HelloWorldController.java
│ ├─ resources/
│ │ └─ springmvc-servlet.xml
│ └─ webapp/
│ ├─ WEB-INF/
│ │ ├─ web.xml
│ │ ├─ views/helloworld.jsp
│ │ └─ springmvc-servlet.xml (或放 resources)
│ └─ index.jsp
<web-app>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern> <!-- 攔截所有,包含靜態資源需額外配置 -->
</servlet-mapping>
</web-app>
<beans xmlns="https://www.springframework.org/schema/beans"
xmlns:context="https://www.springframework.org/schema/context"
xmlns:mvc="https://www.springframework.org/schema/mvc"
xsi:schemaLocation="...spring-mvc-4.2.xsd ...spring-context-4.2.xsd">
<!-- 1. 掃描 Controller 包 -->
<context:component-scan base-package="com.zhy.controllers" />
<!-- 2. 啟用註解驅動 (@RequestMapping, @Autowired, 格式化, 驗證等) -->
<mvc:annotation-driven />
<!-- 3. 視圖解析器:前綴 + 邏輯視圖名 + 後綴 = 物理路徑 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
package com.zhy.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloWorldController {
@RequestMapping("/mvc")
public String hello() {
System.out.println("call controller");
return "helloworld"; // 邏輯視圖名
}
}
視圖解析:`/WEB-INF/views/` + `helloworld` + `.jsp` = `/WEB-INF/views/helloworld.jsp`
<%@ page contentType="text/html;charset=UTF-8" %>
<html><body>
<h2>Hello World! SpringMVC 註解式開發成功</h2>
<p>當前時間:${new java.util.Date()} </p>
</body></html>
<!-- REST 風格:@RequestMapping("/article/details/{id}") + @PathVariable -->
@RequestMapping("/article/details/{id}")
public ModelAndView details(@PathVariable("id") int id) { ... }
<!-- 靜態資源放行:CSS/JS/圖片不經 DispatcherServlet -->
<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:resources mapping="/static/**" location="/static/" />
404:檢查 `url-pattern`、`@RequestMapping` 路徑、視圖解析器前後綴、JSP 物理路徑。註解式 SpringMVC 讓 Web 開發回歸純 Java 代碼,結構清晰、重構安全、擴展靈活。