springboot2.0 使用 Thymeleaf 开发 web 项目简单示例

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cheungmine/article/details/80555372

springboot2.0 使用 Thymeleaf 开发 web 项目简单示例

Spring boot开发web项目,通常打成jar包,使用内置的web服务器 Tomcat、Jetty、undertow 来运行。静态资源(css、js、图片等)默认放在resources/static下面。如果要修改默认存放目录,可以通过设置属性 spring.mvc.static-path-pattern来实现。

模板文件默认放在 templates目录下。Spring boot支持使用模板来开发web应用,支持的模板类型包括:

  • FreeMarker
  • Groovy
  • Thymeleaf
  • Mustache

Spring boot不建议使用jsp开发web。本文使用Thymeleaf来作为模板引擎开发web项目。

Thymeleaf

Thymeleaf是一个Java模板引擎开发库,可以处理和生成HTML、XML、JavaScript、CSS和文本,在Web和非Web环境下都可以正常工作。Thymeleaf可以跟Spring boot很好的集成。

创建项目

在 start.spring.io 网站上创建一个空项目,然后下载到本地。解压后展开的目录如下:

cl@ubuntu64fan:~/Workspace/webapp$ tree

├── mvnw
├── mvnw.cmd
├── pom.xml
└── src
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── pepstack
    │   │           └── webapp
    │   │               ├── controller
    │   │               │   └── UserController.java
    │   │               ├── model
    │   │               │   └── User.java
    │   │               └── WebappApplication.java
    │   └── resources
    │       ├── application.properties
    │       ├── static
    │       └── templates
    │           └── user
    │               ├── detail.html
    │               └── list.html
    └── test
        └── java
            └── com
                └── pepstack
                    └── webapp
                        └── WebappApplicationTests.java

没有的目录和文件是我添加的。更改文件内容如下:

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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.pepstack</groupId>
    <artifactId>webapp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>webapp</name>
    <description>web project for Spring Boot2.0</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

User.java

package com.pepstack.webapp.model;


public class User {
    private Long id;

    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }


    private String username;

    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }


    private String address;

    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }


    private int age;

    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

UserController.java

package com.pepstack.webapp.controller;

import java.util.List;
import java.util.ArrayList;

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

import com.pepstack.webapp.model.User;

// 一定是 Controller, 不能是 RestController
@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping("/{id}") 
    public String  getUser(@PathVariable int id, Model model) {

        User dto = new User();

        dto.setId((long) id);
        dto.setUsername("pepstack-"+id);
        dto.setAddress("Shanghai, China");
        dto.setAge(20 + id);

        model.addAttribute("user", dto);

        return "/user/detail";
    }


    @RequestMapping("/list")
    public String  listUser(Model model) {
        List<User> userList = new ArrayList<User>();

        for (int i = 0; i < 9; i++) {
            User dto = new User();

            dto.setId((long) i);
            dto.setUsername("pepstack-" + i);
            dto.setAddress("Shanghai, China");
            dto.setAge(20 + i);

            userList.add(dto);
        }

        model.addAttribute("users", userList);

        return "/user/list";
    }
}

list.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>list.html</title>
</head>
<body>
  <h2>用户列表</h2>
  <div>
     <ul>
         <li th:each="user:${users}">
             <p>ID:<span th:text="${user.id}"></span></p>
             <p>名字:<span th:text="${user.username}"></span></p>
             <p>年龄:<span th:text="${user.age}"></span></p>
             <p>地址:<span th:text="${user.address}"></span></p>
         </li>
     </ul>
   </div>
</body>
</html>

detail.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>detail.html</title>
</head>
<body>
  <h2>用户信息</h2>
  <div>
     <p>ID:<span th:text="${user.id}"></span></p>
     <p>名字:<span th:text="${user.username}"></span></p>
     <p>年龄:<span th:text="${user.age}"></span></p>
     <p>地址:<span th:text="${user.address}"></span></p>
   </div>
</body>
</html>

application.properties

# url path
server.port=8088
server.servlet.context-path=/webapp

# thymeleaf
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html

# 开发阶段务必关闭缓存 (=false)
spring.thymeleaf.cache=false

运行

# mvn spring-boot:run

浏览器访问

http://localhost:8088/webapp/user/list

http://localhost:8088/webapp/user/2

代码浏览和下载

https://github.com/pepstack/springboot2-webapp-sample01

git clone https://github.com/pepstack/springboot2-webapp-sample01.git

猜你喜欢

转载自blog.csdn.net/cheungmine/article/details/80555372