有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用Thymeleaf、Java和Spring MVC更新HTML数据表

我正在开发一个简单的规划扑克应用程序,使用Java 11Spring Boot 2.1.2Thymeleaf Spring 5

所附图片显示了主页。登录后,用户提交分数。该请求被发送到粘贴在下面的控制器方法,在该方法中,分数被持久化到数据库中。然后,从数据库中以列表的形式检索该组的整套分数。用户的个人分数和组分数列表都被添加到模型中,用户被转发到扑克。html页面

@PostMapping("/score")
public String submitScores(@Valid SimplePoker simplePoker, BindingResult result, Model model) {
    SimplePoker poker = simplePokerRepository.save(simplePoker);
    model.addAttribute("poker_score", poker);

    Iterable<SimplePoker> scores = simplePokerRepository.findAll();
    model.addAttribute("scores", scores);
    return "poker";
}

在扑克上。html页面中,使用标准的Thymeleaf模式生成一个表,如下所示:-

<div class="container" th:if="${not #lists.isEmpty(scores)}">
    <table class="table table-striped table-hover table-bordered table-responsive-md">
        <thead class="thead-dark">
        <tr>
            <th class="text-center, align-middle">Name</th>
            <th class="text-center, align-middle">Planning</th>
            <th class="text-center, align-middle">Business Risk</th>
            <th class="text-center, align-middle">Chance of Failure</th>
            <th class="text-center, align-middle">Total Risk</th>
        </tr>
        </thead>
        <tbody>
        <tr th:each="score: ${scores}">
            <td th:text="${score.name}"></td>
            <td th:text="${score.planningScore}"></td>
            <td th:text="${score.risk1Score}"></td>
            <td th:text="${score.risk2Score}"></td>
            <td th:text="${score.risk3Score}"></td>
        </tr>
        </tbody>
    </table>
</div>

这一切都很好,但当然,表格只代表用户发出请求时的结果。我想在表格下方(黄色突出显示区域)添加一个“更新表格”按钮,用户可以点击该按钮,获取一组新数据,并用最新结果更新页面上的表格。由于我主要是一名后端开发人员,我在这里有点困难,非常感谢您的指导

我想我可以创建一个粗略的解决方案,点击按钮只需刷新整个页面,但只更新表格会更加平滑。如果表格每隔几秒钟自动更新一次,用户就不需要点击按钮,这将是锦上添花。但作为第一步,实现一个更新表格的按钮将是非常棒的

非常感谢您阅读我的帖子并提供任何帮助。 Planning Poker app - the yellow highlight shows where an Update button could go for updating the table


共 (1) 个答案

  1. # 1 楼答案

    你可能想调查一下htmx。这是一个JavaScript库,可以避免自己编写JavaScript来完成这里需要的事情

    您可以像这样添加周期刷新:

    <div hx-trigger="every 1s"
         hx-get="/table" >
    </div>
    

    您可以在最初呈现整个页面时将其添加到ThymleLab模板中。在那之后,htmx将每1秒进行一次GET on /table

    在控制器中,应该返回构建表所需的HTML。如果该表是Thymeleaf片段,则可以重复使用该片段:

    @Controller
    public class MyController {
      @GetMapping("/table")
      public String getTable(Model model) {
        // first fill up your model using .addAttribute
    
        // return the fragment
        return "fragments :: table"
      }
    }
    

    This example也做了类似的事情。另请参见TodoMVC with Thymeleaf and HTMX了解有关将Thymeleaf与htmx结合的一些额外背景信息