前言

在这个教程中,我们将通过一个简单的实例来展示如何使用JSP和Thymeleaf技术实现前后端结合。JSP用于服务器端页面渲染,而Thymeleaf则是一种现代的模板引擎,用于服务器端页面逻辑处理。

环境准备

- Java开发环境(如JDK 1.8及以上)

jsp与Thymeleaf实例教程快速上手前后端结合  第1张

- Java Web开发环境(如Tomcat 9.0及以上)

- IntelliJ IDEA或Eclipse等IDE

实例:简单的用户信息展示

1. 创建项目

在IDE中创建一个Java Web项目,命名为“JspThymeleafExample”。

2. 添加依赖

在项目的`pom.xml`文件中添加以下依赖:

```xml

org.springframework.boot

spring-boot-starter-thymeleaf

org.springframework.boot

spring-boot-starter-web

```

3. 配置文件

在`src/main/resources/application.properties`中添加以下配置:

```properties

spring.thymeleaf.prefix=classpath:/templates/

spring.thymeleaf.suffix=.html

```

4. 创建控制器

在`src/main/java/com/example/jspthymeleafexample`包下创建一个名为`UserController`的控制器类:

```java

package com.example.jspthymeleafexample;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.GetMapping;

@Controller

public class UserController {

@GetMapping("