springboot的默认只支持html需要引入模板引擎
模板引擎:如jsp这样,springboot推荐使用thymeleaf,模板引擎通过模板的语法交给引擎最后生成真正的html渲染的思路。
因此使用启动器引入引擎。
第一个springboot项目
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.yuanyi</groupId>
<artifactId>myspringboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>myspringboot</name>
<description>Demo project for Spring Boot</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<!--适配版本模板引擎-->
<thymeleaf.verson>3.0.12.RELEASE</thymeleaf.verson>
<thymeleaf-layout-dialect.version>2.5.2</thymeleaf-layout-dialect.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--模板引擎-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
thymeleaf
thymeleaf-layout-dialect都可在git-hub中搜索到
templates是前端页面的存放目录
controller
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Controller
public class HelloController {
@RequestMapping("/toHello")
public String toHello(Map<String,Object> user){
List<Object> list=new ArrayList<>();
list.add("你好");
list.add(5);
user.put("user",list);
return "hello";
}
}
html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"><!--添加模板命名空间-->
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:each="item:${user}" th:text="${item}">
</div>
</body>
</html>
访问
http://localhost:8080/toHello
网友评论