Spring MVC 在 GetMapping 后停止刷新页面

Spring MVC stop refreshing the page after GetMapping

我正在处理一个页面,在该页面上我必须从数据库中检索特定日期的“任务”。我目前的做法是在服务器端使用GetMapping,return任务列表

下面是我的一部分TaskController

@Controller
@RequestMapping()
public class TaskController {

    @Autowired
    private TaskService taskService;

    @GetMapping("/calendar/{date}")
    public String displayTasksByClick(@PathVariable("date") int date, Model model) {
    
        long userId = this.getCurrentUserId(); // just a method to get the user id requesting the task

        List<Task> taskList = taskService.findByDateAndUserId(date, userId); 
        model.addAttribute("taskList", taskList);
        return "/calendar";
    }

calendar.html看起来像这样(我只粘贴了相关部分)

<html lang='en' xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset='utf-8' />
        <title>Dashboard</title>
        <link rel="stylesheet" href="../static/css/calendar.css">
        <script src="jquery-3.5.1.min.js"></script>
  </head>
  <body>
      <ul style="list-style-type: none; margin: 0;">
        <li><a th:href="@{/calendar/20220228}">show</a></li>
        <li><a th:href="@{/calendar/20220301}">show</a></li>
        <li><a th:href="@{/calendar/20220301}">show</a></li>
      </ul>
  ......
       <div th:each="task : ${taskList}">
           <label th:text="${task.name}"></label>
       </div>

  <!-- the rest is irrelevant to the question --!>
  .......
 </html>

因此,每当我单击 <a> 元素时,客户端都会向服务器发送请求,并且 URL 由 GetMapping 方法处理,returning 任务。但是,在发生这种情况时,页面也会刷新。有没有一种不用刷新页面就能显示任务的方法?

我尝试从显示方法中 returning void,但是 Spring 自动结束 returning /calendar/{date},这仍然不是我想要的

@GetMapping("/calendar/{date}")
public void displayTasksByClick(@PathVariable("date") int date, Model model) {
    
    long userId = this.getCurrentUserId(); // just a method to get the user id requesting the task

    List<Task> taskList = taskService.findByDateAndUserId(date, userId);
    model.addAttribute("taskList", taskList);
}

对于您当前的实施,不,这是不可能的。您必须刷新页面才能显示任务。这就是服务器端渲染的工作方式。在服务器上用动态数据创建页面,然后将静态页面返回给浏览器。