Spring Boot MVC示例

x33g5p2x  于2022-10-04 转载在 Spring  
字(4.4k)|赞(0)|评价(0)|浏览(381)

在本教程中,我们将学习如何创建一个基于**Spring MVC模式的应用程序,并使用模板引擎Thymeleaf渲染页面视图。

设置MVC项目

开箱后,Spring BootSpring MVC提供了默认配置。而当你把模板引擎带入项目时,你也会得到所有需要的视图解析器,以便从标准JSP编程转移到现代模板引擎。

让我们从**Spring Boot Initializer开始,选择 "Web "和 "Thymeleaf "作为你项目的依赖。下载并解压该项目到你的硬盘上。

在你最喜欢的IDE中导入项目,让我们开始为它添加代码吧

这就是最初的项目结构。

src
├── main
│   ├── java
│   │   └── com
│   │       └── example
│   │           └── demo
│   │               └── DemoApplication.java
│   └── resources
│       ├── application.properties
│       ├── static
│       └── templates
└── test
    └── java
        └── com
            └── example
                └── demo
                    └── DemoApplicationTests.java

视图的编码

在模板目录中,我创建了一个名为persons.html的新HTML文件。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
   <head>
      <title>Spring Boot Thymeleaf Hello World Example</title>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
   </head>
   <body>
      <h1>MasterSpringBoot</h1>
      <h2>Spring Boot Thymeleaf Hello World Example</h2>
      
            <table border="1" class="table">
                <thead>
                    <tr>
                        <th>First Name</th>
                        <th>Last Name</th>
                    </tr>
                </thead>
                <tbody>
                    <tr th:each="person : ${persons}">
                        <td th:text="${person.name}"></td>
                        <td th:text="${person.surname}"></td>
                    </tr>

                </tbody>
            </table>
            
   </body>
</html>

从上面的代码可以看出,我需要对我的HTML文件做的第一件事就是为Thymeleaf添加XML命名空间。

在页面中,我们要显示一个HTML表格,使用一个迭代器来显示模型中加载的所有Person对象。为了做到这一点,我们使用th:each迭代模型中的人员列表并创建一个新的Person对象。神奇的是,Thymeleaf能够在我们进行过程中为我解决这个问题。

一旦完成了对人员的迭代,我们需要使用th:text标签来填充表格单元,该标签引用了Person对象的属性。

对模型进行编码

下一步,我们将在HTML中添加一个具有我们已经看到的属性(名字、姓氏)的Person模型对象。

package com.example.demo;

public class Person {
  private String name;
  private String surname;

  public Person(String name, String surname) {
    super();
    this.name = name;
    this.surname = surname;
  }

  public Person() {
    super();
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getSurname() {
    return surname;
  }

  public void setSurname(String surname) {
    this.surname = surname;
  }
}

编码控制器

最后,我们需要一个控制器给我们的Person对象,所以我们将创建一个PersonController类。

package com.example.demo;

import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Controller
@RequestMapping("/persons")
public class PersonController {
  private static List<Person> persons = new ArrayList();

  static {
    Person p1 = new Person("Jack", "Smith");
    Person p2 = new Person("Lucas", "Derrik");
    Person p3 = new Person("Andy", "Miller");
    persons.add(p1);
    persons.add(p2);
    persons.add(p3);
  }

  @GetMapping
  public String getAllPersons(Model model) {
    model.addAttribute("persons", persons);
    return "persons";
  }
}

我们用**@Controller**来注解这个类,这样它就可以被组件扫描了。而且我们还需要一个RequestMapping。在这个类中,我们需要添加一些样本数据。为了简单起见,我们将静态地创建一个Person的列表。

现在,一旦完成,让我们创建一个GetMapping。我们将返回一个名为getAllPersons的公共字符串。在这个方法的参数中,我们将传递一个叫做Model的对象,它是org.spring框架UI包中的一个对象。

这个对象将在你的视图中以 "人 "的名义出现。正如你所看到的,该方法也返回 "persons",这只是你的视图的名称。

运行应用程序

最后,我们能够运行应用程序,并请求获得http://localhost:8080/persons

下面是Thymeleaf产生的视图。

添加CSS和Javascript

为了改进我们的例子,我们将添加一些静态资源,如CSS和Javascript。首先,你应该把这些资源放在resources/static文件夹下,如下面的目录树。

src/main/resources/
├── application.properties
├── static
│   ├── css
│   │   └── main.css
│   └── js
│       └── functions.js
└── templates
    └── persons.html

所以我们已经添加了以下资源。

main.css - 这是一个样式表,用于自定义视图的外观。
functions.js - 这是一个javascript文件,它包含一个我们将在主页面加载时触发的函数。

这里是main.css。

h1{ 	color:#0000FF; }  h2{ 	color:#FF0000; }

最后,这是 functions.js。

function hello() {
    alert("Hello from Spring MVC");
}

为了包括上述静态资源,我们将更新我们的HTML页面的HEAD部分,如下所示。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE HTML> 
<html xmlns:th="http://www.thymeleaf.org">
 <head> <title>Spring Boot Thymeleaf Hello World Example</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> 
    <link th:href="@{/css/main.css}" rel="stylesheet" /> 
    <script type="text/javascript" th:src="@{/js/functions.js}"></script>
</head>
   <body onload="hello()">
     <!-- Unchanged -->

   </body>
</html>

这就是了。再次检查persons.html页面,看看是否有变化。

本教程的源代码:https://github.com/fmarchioni/masterspringboot/tree/master/mvc/mvc-demo

相关文章

微信公众号

最新文章

更多