Home > Enterprise >  Spring MVC stop refreshing the page after GetMapping
Spring MVC stop refreshing the page after GetMapping

Time:03-09

I am working on a page where I have to retrieve the "tasks" of a specific date from the database. My current approach is to use GetMapping at the server, and return the list of tasks

Below is part of my 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";
    }

And calendar.html looks like this (I'm only pasting the relevant part)

<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>

So whenever I click on the <a> elements, the client sends a request to the server, and the URL is handled by GetMapping method, returning the tasks. But while this happens, the page is also refreshed. Is there a way to display the tasks without having to refresh the page?

I tried returning void from the display method, but Spring ends up automatically returning /calendar/{date}, and it's still not what I want

@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);
}

CodePudding user response:

For your current implementation, no, it is not possible. You have to refresh the page for the tasks to be displayed. That's how server side rendering works. The page is created on the server with the dynamic data, then the static page is returned to the browser.

  • Related