使用 IDEA + Maven 搭建传统 Spring MVC + Thymeleaf 项目的详细步骤

使用 IDEA + Maven 搭建传统 Spring MVC + Thymeleaf 项目

      • 环境准备
      • [步骤 1:创建 Maven 项目](#步骤 1:创建 Maven 项目)
      • [步骤 2:添加依赖(pom.xml)](#步骤 2:添加依赖(pom.xml))
      • [步骤 3:配置 web.xml](#步骤 3:配置 web.xml)
      • [步骤 4:Spring 配置类(Java Config)](#步骤 4:Spring 配置类(Java Config))
      • [步骤 5:编写 Controller](#步骤 5:编写 Controller)
      • [步骤 6:创建 Thymeleaf 模板](#步骤 6:创建 Thymeleaf 模板)
      • [步骤 7:添加静态资源](#步骤 7:添加静态资源)
      • [步骤 8:部署到 Tomcat](#步骤 8:部署到 Tomcat)
      • 最终效果

环境准备

  1. IDE: IntelliJ IDEA
  2. JDK:1.8+
  3. 构建工具:Maven
  4. 服务器:Tomcat 9+

步骤 1:创建 Maven 项目

  1. 打开IDEA -> New Project

  2. 选择 Maven -> 勾选 Create from archetype -> 选择 maven-archetype-webapp

  3. 填写 GroupId 和 ArtifactId(如:com.example / springmvc-demo)

  4. 项目结构如下:

    复制代码
    src/
    ├─ main/
    │  ├─ java/
    │  │  └─ com/example/controller/   # Controller 代码
    │  │  └─ config/                   # Spring 配置类
    │  ├─ webapp/
    │  │  ├─ WEB-INF/
    │  │  │  └─ views/                 # Thymeleaf 模板
    │  │  └─ static/                   # 静态资源(CSS/JS)
    │  └─ resources/                   # 配置文件(可选)

步骤 2:添加依赖(pom.xml)

xml 复制代码
<dependencies>
    <!-- Spring MVC -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.20</version>
    </dependency>

    <!-- Thymeleaf 集成 Spring -->
    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf-spring5</artifactId>
        <version>3.0.15.RELEASE</version>
    </dependency>

    <!-- Servlet API -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

步骤 3:配置 web.xml

xml 复制代码
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
    <display-name>Spring MVC App</display-name>

    <!-- 配置 DispatcherServlet -->
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextClass</param-name>
            <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
        </init-param>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>com.example.config.WebConfig</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!-- 映射所有请求到 DispatcherServlet -->
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

步骤 4:Spring 配置类(Java Config)

创建 WebConfig.java:

java 复制代码
package com.example.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

@Configuration
@EnableWebMvc
@ComponentScan("com.example.controller")  // 扫描 Controller
public class WebConfig implements WebMvcConfigurer {

    // 配置 Thymeleaf 模板解析器
    @Bean
    public SpringResourceTemplateResolver templateResolver() {
        SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
        resolver.setPrefix("/WEB-INF/views/");  // 模板路径
        resolver.setSuffix(".html");           // 文件后缀
        resolver.setTemplateMode("HTML");
        resolver.setCharacterEncoding("UTF-8");
        return resolver;
    }

    // 配置 Thymeleaf 模板引擎
    @Bean
    public SpringTemplateEngine templateEngine() {
        SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setTemplateResolver(templateResolver());
        return engine;
    }

    // 配置视图解析器
    @Bean
    public ThymeleafViewResolver viewResolver() {
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(templateEngine());
        resolver.setCharacterEncoding("UTF-8");
        return resolver;
    }

    // 配置静态资源(CSS/JS)
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**")
                .addResourceLocations("/static/");
    }
}

步骤 5:编写 Controller

创建 HomeController.java:

java 复制代码
package com.example.controller;

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

@Controller
public class HomeController {

    @GetMapping("/")
    public String home(Model model) {
        model.addAttribute("message", "Hello, Thymeleaf!");
        return "home";  // 对应 WEB-INF/views/home.html
    }
}

步骤 6:创建 Thymeleaf 模板

在 /WEB-INF/views/ 下新建 home.html:

html 复制代码
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Spring MVC + Thymeleaf</title>
    <link th:href="@{/static/css/style.css}" rel="stylesheet">
</head>
<body>
    <h1 th:text="${message}">Default Message</h1>
    <script th:src="@{/static/js/app.js}"></script>
</body>
</html>

步骤 7:添加静态资源

  1. 在 /webapp/static/css/ 下创建 style.css:

    css 复制代码
    h1 { color: blue; }
  2. 在 /webapp/static/js/ 下创建 app.js:

    javascript 复制代码
    console.log("Static JS loaded!");

步骤 8:部署到 Tomcat

  1. 在 IDEA/Eclipse 中配置 Tomcat 服务器。
  2. 将项目添加到 Tomcat 并启动。
  3. 访问 http://localhost:8080/,会看到蓝色字体的 Hello, Thymeleaf!。

最终效果

  • 动态数据通过 th:text 渲染。
  • 静态资源(CSS/JS)被正确加载。
  • 项目结构清晰,适合传统 Spring MVC 开发。
相关推荐
猿究院_夏燊9 小时前
Spring Bean 生命周期
java·后端·spring
砚底藏山河10 小时前
python量化:行情数据回溯
java·开发语言·python·金融·maven
流烟默11 小时前
MCP第 5 篇:用 Spring AI 写 MCP:注解、自动配置、ChatClient 集成
人工智能·spring·mcp封装
来福猿13 小时前
SpringCloud Config 源码分析:配置拉取、刷新与多环境管理
后端·spring·spring cloud
雷一言说16 小时前
Spring AI 2.0 RAG:用 Metadata Filter 做多租户检索隔离
java·spring
摇滚侠17 小时前
《大模型应用开发实践:基于 Spring AI+DeepSeek 实现》第 11 章 大模型技术概览 阅读笔记 1
人工智能·笔记·spring
毕业设计70320 小时前
(免费领源码)SSM董家湾线上点餐系统04682- java、PHP、python、C#、小程序、大数据、单片机、网络工程等)
java·redis·mysql·tomcat·maven·mybatis·ssm
技术小结-李爽21 小时前
【工具】怎么在终端中启动springboot项目?
java·spring boot·后端·maven
知守观1 天前
Maven 依赖仲裁实战:pom 里写的 2.0,为什么打出的 WAR 包是 1.5?
java·后端·maven
一枕槐安4871 天前
大模型应用后端设计:上下文管理、缓存、降级策略的工程方案总结
java·spring·缓存