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

环境准备

  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)

<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

<!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

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

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

<!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
    h1 { color: blue; }
    
  2. /webapp/static/js/ 下创建 app.js
    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 开发。

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员buddha2080

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值