首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Spring MVC 入門指南:從零搭建 Spring MVC 專案

     編輯:Java 綜合教學

Spring MVC 入門指南:從零搭建 Spring MVC 專案

Spring MVC 是 Spring 框架中用於構建 Web 應用程式的核心模組,採用 MVC(Model-View-Controller)設計模式,將業務邏輯、資料展示與控制流程分離。本文將詳細介紹如何從零開始搭建一個 Spring MVC 專案,包含專案結構規劃、核心配置檔案編寫、控制器實現與視圖渲染等關鍵步驟。

Spring MVC 核心架構圖解

在動手實作前,先理解 Spring MVC 的請求處理流程:

Spring MVC 架構圖

核心組件說明:

  • DispatcherServlet:前端控制器,接收所有請求並委派給對應組件處理
  • HandlerMapping:處理器映射器,根據 URL 找到對應的 Controller
  • HandlerAdapter:處理器適配器,執行 Controller 並返回 ModelAndView
  • ViewResolver:視圖解析器,將邏輯視圖名解析為具體視圖實現

專案結構與配置檔案

1. 建立專案目錄結構

建立標準 Maven Web 專案結構,並在 src/main/resources 下建立 config 資料夾存放配置檔案。

2. 配置 web.xml - 註冊前端控制器

<web-app version="2.5" xmlns="https://java.sun.com/xml/ns/javaee"
    xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="https://java.sun.com/xml/ns/javaee 
    https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <display-name>SpringMVCDemo</display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    
    <!-- 配置 Spring MVC 前端控制器 -->
    <servlet>
        <servlet-name>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 指定 Spring MVC 配置檔案路徑 -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <!-- 攔截以 .action 結尾的請求 -->
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>
</web-app>

3. 配置 applicationContext-mvc.xml - Spring MVC 核心配置

<beans xmlns="https://www.springframework.org/schema/beans"
    xmlns:aop="https://www.springframework.org/schema/aop"
    xmlns:context="https://www.springframework.org/schema/context"
    xmlns:mvc="https://www.springframework.org/schema/mvc"
    xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        https://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        https://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context-4.0.xsd
        https://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
    
    <!-- 開啟組件掃描,自動註冊 @Controller 等註解標記的 Bean -->
    <context:component-scan base-package="com.mvc" />
    
    <!-- 手動註冊 Handler(也可使用註解方式) -->
    <bean class="com.mvc.action.HelloAction" name="/hello.action"></bean>
    
    <!-- 處理器映射器:根據 Bean 名稱映射 URL -->
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>
    
    <!-- 處理器適配器:支援 Controller 介面實現類 -->
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>
    
    <!-- 視圖解析器:配置 JSP 視圖路徑前綴與後綴 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
    
    <!-- 開啟註解驅動,支援 @RequestMapping 等註解 -->
    <mvc:annotation-driven />
</beans>

Spring 核心 Jar 包依賴說明

Spring Jar 包列表

搭建 Spring MVC 專案需要引入以下核心依賴(建議使用 Maven 管理):

Jar 包功能描述主要依賴
spring-core.jar核心工具類,所有模組基礎commons-logging
spring-beans.jarIoC/DI 容器核心實現spring-core, cglib
spring-context.jarApplicationContext、驗證、JNDI 等擴展spring-beans, spring-aop
spring-web.jarWeb 應用核心支援,含檔案上傳、Filter 等spring-context, Servlet API
spring-webmvc.jarSpring MVC 框架實現,含 Servlet、Controller、Viewspring-web, spring-context
spring-aop.jarAOP 實現,支援聲明式事務spring-beans, aopalliance, cglib
aopalliance.jarAOP 聯盟標準介面-

依賴關係圖

依賴關係總結: spring-core 為基礎 → spring-beans → spring-aop → spring-context → spring-web → spring-webmvc。實際開發中強烈建議使用 Maven 或 Gradle 自動管理傳遞性依賴。

控制器實現

實作 Controller 介面(傳統方式)

package com.mvc.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class HelloAction implements Controller {
    @Override
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String message = "Hello World! Spring MVC 搭建成功!";
        
        ModelAndView modelAndView = new ModelAndView();
        // 設定模型資料,相當於 request.setAttribute()
        modelAndView.addObject("message", message);
        // 設定邏輯視圖名,經 ViewResolver 解析為 /WEB-INF/jsp/hello.jsp
        modelAndView.setViewName("hello");
        
        return modelAndView;
    }
}

現代註解式寫法(推薦)

package com.mvc.action;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.Model;

@Controller
@RequestMapping("/hello")
public class HelloController {
    
    @RequestMapping("/world.action")
    public String helloWorld(Model model) {
        model.addAttribute("message", "Hello World! 使用註解式開發更簡潔");
        return "hello";  // 邏輯視圖名
    }
    
    @RequestMapping("/api/message")
    @ResponseBody
    public String apiMessage() {
        return "{\"message\": \"REST API 回傳 JSON\"}";
    }
}

視圖頁面實現

hello.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Spring MVC 入門範例</title>
</head>
<body>
    <h1>Spring MVC 測試頁面</h1>
    <p>伺服器回傳訊息:<strong>${message}</strong></p>
    <hr/>
    <p>當前時間:${new java.util.Date()}</p>
</body>
</html>

專案結構圖

專案結構

啟動驗證

  1. 將專案部署至 Tomcat 等 Servlet 容器
  2. 啟動伺服器
  3. 瀏覽器訪問:https://localhost:8080/專案名/hello.action(傳統模式)或 https://localhost:8080/專案名/hello/world.action(註解模式)
  4. 頁面應顯示「Hello World! Spring MVC 搭建成功!」

常見問題與解決方案

  • 404 錯誤:檢查 url-pattern 是否與請求 URL 匹配,Controller 映射路徑是否正確
  • 視圖解析失敗:確認 prefix/suffix 配置與實際 JSP 路徑一致
  • 中文亂碼:在 web.xml 配置 CharacterEncodingFilter,JSP 頁面指定 charset=UTF-8
  • Jar 包衝突:使用 Maven 依賴管理,排除傳遞性依賴衝突

進階擴展建議

  • 整合 MyBatis/Hibernate 實現資料持久層
  • 配置攔截器實現登入驗證、日誌記錄
  • 使用 @RestController 開發 RESTful API
  • 整合 Swagger 生成 API 文檔
  • 配置異常統一處理機制

至此,一個基礎的 Spring MVC 專案已搭建完成。掌握核心配置原理後,建議逐步遷移至 Spring Boot 以獲得更高的開發效率與生產級預設配置。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved