【问题标题】:Generating hyperlinks with Thymeleaf, Spring Boot使用 Thymeleaf、Spring Boot 生成超链接
【发布时间】:2018-08-16 19:57:42
【问题描述】:

我在使用 Thymeleaf 生成 html 链接时遇到问题。我使用过 jpa 并且有 2 个表('users' 和 'selectedUsers') 我已经创建了一个 html 页面,其中表 'users' 显示为列表。

它可以工作,但我想向此列表的每个生成的元素添加一个超链接,该超链接将为“selectedUsers”表添加值。控制器应该是对的,但我不知道如何生成链接

http://localhost:8080/selectedusers/create?name=<name of current element in 'users table'>

如果无法使用 thymeleaf 生成,也许还有另一种方法可以将值插入 selectedUsers。

HTML页面:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>All users</title>
</head>
<body>
<div id="container">
    <h1> List of all users: </h1>
    <ul th:each="user : ${users}">
        <div id="list">
            User data:
            <p th:text="${user.name} + ' | ' + ${user.email}"></p>
            <a href="/selectedusers/create?name=      ">Click here to add 
            this user to another table in database</a>
        </div>
    </ul>
</div>
</body>
</html>

部分控制器:

@GetMapping("/find-all-users")
public String findUsers(Model model) {
    model.addAttribute("users", userDao.findAll());
    return "findusers";
}

@Autowired
private SelectedUserDao selectedUserDao;

@RequestMapping("/selectedusers/create")
public String create(@RequestParam("name") String name) {
    String selectedUserId="";

    SelectedUser selectedUser= new SelectedUser(name);
    selectedUserDao.save(selectedUser);
    selectedUserId = String.valueOf(selectedUser.getId());
    return "findusers";
}

【问题讨论】:

    标签: html spring spring-boot thymeleaf


    【解决方案1】:

    documentation 中所述,您可以使用thymeleaf 标准方言。

    <a th:href="@{/selectedusers/create(name=${user.name})}">Click here to add 
                    this user to another table in database</a>
    

    在内部这将产生一个这样的链接:

    /selectedusers/create?name=anyName

    【讨论】:

      猜你喜欢
      • 2020-11-26
      • 2019-12-30
      • 2017-05-07
      • 2015-07-01
      • 2017-11-28
      • 1970-01-01
      • 2019-01-30
      • 2016-09-23
      • 2019-05-21
      相关资源
      最近更新 更多