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

Spring MVC + Maven 在 IntelliJ IDEA 中從零搭建完整教程

     編輯:Java 綜合教學

Spring MVC + Maven 在 IntelliJ IDEA 中從零搭建完整教程

IntelliJ IDEA 是公認最強 Java IDE,配合 Maven 依賴管理,能讓 Spring MVC 專案搭建事半功倍。本教程涵蓋專案創建、依賴配置、核心 XML 配置、控制器編寫、運行驗證全流程。

一、創建 Maven Web 專案

  1. File → New → Project... → 左側選 Maven → 勾選 Create from archetype → 選 maven-archetype-webapp → Next
    New Project
  2. 填寫 GroupId、ArtifactId、Version(如 `cn.qixiao` / `Liuyanban_SpringMVC` / `1.0-SNAPSHOT`) → Next
    Maven Coordinates
  3. 指定 Maven 本地倉庫路徑、settings.xml 路徑 → Next
    Maven Settings
  4. 專案名稱與存放路徑 → Finish
    Project Name
  5. IDEA 自動導入 Maven 依賴,右下角彈窗選 Enable Auto-Import

二、補全目錄結構並標記根目錄

Maven 標準目錄:

src
├── main
│   ├── java          → Mark as Sources Root (藍色)
│   ├── resources     → Mark as Resources Root
│   └── webapp
│       └── WEB-INF
│           └── web.xml
└── test
    ├── java          → Mark as Test Sources Root (綠色)
    └── resources     → Mark as Test Resources Root

操作:右鍵目錄 → Mark Directory as → 選對應類型。

Mark Directory

三、配置 pom.xml 依賴

<project xmlns="https://maven.apache.org/POM/4.0.0" ...>
    <modelVersion>4.0.0</modelVersion>
    <groupId>cn.qixiao</groupId>
    <artifactId>Liuyanban_SpringMVC</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <spring.version>4.3.1.RELEASE</spring.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <!-- JUnit -->
        <dependency>
            <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version>
        </dependency>

        <!-- Spring Core -->
        <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency>
        <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency>
        <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency>

        <!-- Spring Web MVC -->
        <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency>
        <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency>

        <!-- Database -->
        <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>6.0.3</version> </dependency>
        <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency>

        <!-- JSTL (解決 NoClassDefFoundError: javax/servlet/jsp/jstl/core/Config) -->
        <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency>
    </dependencies>

    <build>
        <finalName>Liuyanban_SpringMVC</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <port>8080</port>
                    <path>/</path>
                    <uriEncoding>UTF-8</uriEncoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

保存後 IDEA 自動下載 JAR 包至本地倉庫。

四、核心配置文件

1. web.xml

<web-app xmlns="https://java.sun.com/xml/ns/javaee" version="3.0">
    <welcome-file-list><welcome-file>/index.jsp</welcome-file></welcome-file-list>

    <!-- Spring MVC DispatcherServlet -->
    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- Spring 容器監聽器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
</web-app>

2. spring-servlet.xml (Spring MVC 配置)

<beans xmlns="https://www.springframework.org/schema/beans"
       xmlns:mvc="https://www.springframework.org/schema/mvc"
       xmlns:context="https://www.springframework.org/schema/context"
       xsi:schemaLocation="...spring-mvc-3.1.xsd">

    <mvc:annotation-driven/>
    <context:component-scan base-package="liuyanban.controller"/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <mvc:resources location="/images/" mapping="/images/**"/>
    <mvc:resources location="/scripts/" mapping="/scripts/**"/>
    <mvc:resources location="/styles/" mapping="/styles/**"/>
</beans>

3. applicationContext.xml (業務層配置,此處為空,擴展用)

<beans ...><!-- DataSource, TransactionManager, Service Bean 等放這裡 --></beans>

五、編寫測試控制器

package liuyanban.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/Test")
public class TestController {

    @RequestMapping("/returnSuccess")
    public String returnSuccess() {
        return "/Views/success";  // 對應 /Views/success.jsp
    }

    @RequestMapping(value = "/returnString", produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String returnString() {
        return "hello return string 這是中文,並沒有亂碼";
    }
}

六、運行與驗證

  1. 右鍵專案 → Run As → Maven Build... → Goals 輸入 `tomcat7:run` → Run(或直接運行 Tomcat 插件配置)。
  2. 瀏覽器訪問:
    `https://localhost:8080/Test/returnString` → 返回純文本,中文正常
    `https://localhost:8080/Test/returnSuccess` → 轉發到 success.jsp 顯示 "success"
    返回字符串
    返回視圖

七、常見坑點與解決

問題原因解決
404 Not Foundurl-pattern 配置錯誤或 Controller 掃描包路徑不匹配檢查 web.xml `/` 及 component-scan base-package
中文亂碼未設置 produces 或 ViewResolver 編碼@RequestMapping(produces="text/plain;charset=UTF-8") 或配置 CharacterEncodingFilter
JSP 不解析缺少 jstl 依賴或 ViewResolver 前綴後綴錯誤添加 jstl:jstl:1.2,prefix="/", suffix=".jsp"
靜態資源 404DispatcherServlet 攔截了靜態請求配置 <mvc:resources mapping="/static/**" location="/static/"/>
依賴衝突Spring 版本不一致統一使用 ${spring.version} 屬性,排除傳遞依賴

總結

通過 Maven 管理依賴、IDEA 智能提示、Spring MVC 註解驅動開發,可快速構建規範、可維護的 Web 應用。掌握核心配置邏輯(DispatcherServlet、HandlerMapping、ViewResolver、Interceptor),才能在遇到疑難雜症時游刃有餘。

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