华域联盟 vbs Springboot Thymeleaf数据迭代实现过程

Springboot Thymeleaf数据迭代实现过程

在模板文件中,可以使用“${{...}}”表达式进行数据转换,Thymeleaf会使用配置好的数据转换类,来实现转换。

例如一个User对象,简单起见假设有姓名和年龄两个字段,对象的toString()方法拼接所有字段,使用“${user}”会调用对象的toString()方法得到所有字段,如果在模板中只想得到姓名,可以使用自定义数据转换类实现。

在Sprint Boot中,实现过程:

(1)先实现自定义的Formatter类,并根据具体业务实现数据转换逻辑;

(2)将自定义的Formatter类注册到容器中;

(3)在模板中使用“${{...}}”表达式。

开发环境:IntelliJ IDEA 2019.2.2

Spring Boot版本:2.1.8

新建一个名称为demo的Spring Boot项目。

1、pom.xml

加入Thymeleaf依赖

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

2、src/main/java/com/example/demo/User.java

package com.example.demo;

public class User {
  String name;
  Integer age;

  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public Integer getAge() {
    return age;
  }
  public void setAge(Integer age) {
    this.age = age;
  }

  @Override
  public String toString() {
    return "User{" +
        "name='" + name + '\'' +
        ", age=" + age +
        '}';
  }
}

3、src/main/java/com/example/demo/UserFormatter.java

实现自定义的Formatter类

package com.example.demo;

import org.springframework.format.Formatter;

import java.text.ParseException;
import java.util.Locale;

public class UserFormatter implements Formatter<User> {

  /**
   * 字符串转换为对象
  */
  @Override
  public User parse(String s, Locale locale) throws ParseException {
    return null;
  }

  /**
   * 对象转换为字符串
   */
  @Override
  public String print(User user, Locale locale) {
    return "name:" + user.getName();
  }
}

4、src/main/java/com/example/demo/MyConfig.java

将自定义的Formatter类注册到容器中

package com.example.demo;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyConfig {
  @Bean
  public UserFormatter userFormatter(){
    return new UserFormatter();
  }
}

5、src/main/java/com/example/demo/TestController.java

package com.example.demo;

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

@Controller
public class TestController {
  @RequestMapping("/")
  public String test(Model model){
    User user = new User();
    user.setName("lc");
    user.setAge(30);
    model.addAttribute("user", user);
    return "test";
  }
}

6、src/main/resources/templates/test.html

<div th:text="${user}"></div>
<div th:text="${{user}}"></div>

浏览器访问:http://localhost:8080

页面输出:

User{name='lc', age=30}
name:lc

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持华域联盟。

您可能感兴趣的文章:

本文由 华域联盟 原创撰写:华域联盟 » Springboot Thymeleaf数据迭代实现过程

转载请保留出处和原文链接:https://www.cnhackhy.com/14915.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部