通過入門程序梳理 Spring MVC 四大核心組件(前端控制器、處理器映射器、處理器適配器、視圖解析器)的配置要點,提供非註解與註解兩套完整可用的配置模板,便於項目快速啟動與遷移。
| 組件 | 非註解模式 | 註解模式(推薦) |
|---|---|---|
| 前端控制器 | *.action 或 / (RESTful) | 同左 |
| 處理器映射器 | BeanNameUrlHandlerMapping | RequestMappingHandlerMapping 或 <mvc:annotation-driven/> |
| 處理器適配器 | SimpleControllerHandlerAdapter | RequestMappingHandlerAdapter 或 <mvc:annotation-driven/> |
| 視圖解析器 | InternalResourceViewResolver (JSP) | 同左 |
關鍵規則:註解映射器與適配器必須成對使用;<mvc:annotation-driven/> 自動註冊兩者並啟用眾多預設功能(JSON 轉換、參數綁定、JSR-303 等),實戰首選。
<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="https://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans-4.0.xsd
https://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
https://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- Handler: Bean 名稱即 URL -->
<bean name="/queryItems.action" class="com.iot.ssm.controller.ItemsController"/>
<!-- 非註解映射器 -->
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<!-- 非註解適配器 -->
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
<!-- 視圖解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"/>
</beans>
<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="https://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans-4.0.xsd
https://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
https://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 掃描 Controller -->
<context:component-scan base-package="com.iot.ssm.controller"/>
<!-- 一鍵啟用註解映射器、適配器、參數綁定、JSON轉換、JSR-303等 -->
<mvc:annotation-driven/>
<!-- 視圖解析器:配置 JSP 路徑前綴/後綴 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
<mvc:annotation-driven/>prefix/suffix,Controller 僅返回邏輯視圖名收藏此文,新建 Spring MVC 項目即刻可用。