路径变量随着分页而变化,错误:无法将类型 java.lang.String 的值转换为所需类型 'java.lang.Long For input string: "{id}"

Path variable changes with pagination, err: Failed to convert value of type java.lang.String to required type 'java.lang.Long For input string: "{id}"

html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>End Value</title>
    <link th:href="@{/static/css/bootstrap.min.css}" rel="stylesheet"/>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"/>
    <style>
#simulat {
  font-family: Arial, Helvetica, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

#simulat td, #plantEvent th {
  border: 1px solid #ddd;
  padding: 8px;
}

#simulat tr:nth-child(even){background-color: #f2f2f2;}

#simulat tr:hover {background-color: #ddd;}

#simulat th {
  padding-top: 12px;
  padding-bottom: 12px;
  text-align: left;
  background-color: #04AA6D;
  color: white;
}
</style>
</head>
<body>
<br>
<td>
    <a th:href="@{~/SimulationsForm}" class="btn btn-primary">Back to simulation form site</a>
    <a th:href="@{~/SimulationsValues}" class="btn btn-primary">Back to simulation values site</a>
</td>
<table id="simulat" border="1" class="table table-striped table-responsive-md">
    <thead>
    <tr>
        <th>Pv</th>
        <th>Pr</th>
        <th>Pi</th>
        <th>Pm</th>
    </tr>
    </thead>
    <tbody>
    <tr th:each="sim, iStat : ${allP.content}"
        th:style="${iStat.odd}? 'font-weight: bold;'"
        th:alt-title="${iStat.even}? 'even' : 'odd'">
        <td th:text="${sim.healthy_Prone_To_Infection}"></td>
        <td th:text="${sim.regained_Health_And_Immunity}"></td>
        <td th:text="${sim.number_Of_Infected}"></td>
        <td th:text="${sim.dead}"></td>
    </tr>
    </tbody>
</table>
<div style="display: inline" th:if="${allP.totalPages > 0}" class="pagination"
     th:each="pageNumber : ${pageNumbers}">
    <a th:href="@{/SimulationsValuesById/{id}/(size=${allP.size}, page=${pageNumber})}"
       th:text=${pageNumber}
       th:class="${pageNumber==allP.number + 1} ? active"></a>
</div>
<br>
Provide simulation name
<input id="vall2" type="text" class="form-control col-2">
<br>
Provide day
<input id="vall3" type="text" class="form-control col-2"><br>
<button onclick="myFunction2()" class="btn btn-primary">Find simulation values for given day for specific simulation by
    name
</button>
<br>
<br>
<br>
Simulations:
<br>
<table>
    <thead>
    <tr class="table-striped">
        <th>Name</th>
        <th>Days</th>
    </tr>
    </thead>
    <tbody>
    <th:block th:each="sim : ${s}">
        <tr>
            <td th:text="${sim.simulation_Name}"></td>
            <td th:text="${sim.simulation_Time}"></td>
        </tr>
    </th:block>
    </tbody>
</table>
<br>
<script>
function myFunction2() {
  var intt = document.getElementById("vall2").value;
  var intt2 = document.getElementById("vall3").value;
location.href = 'http://localhost:8080/SimulationsValues/'+intt+'/'+intt2;
}
</script>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</html>

控制器

 @GetMapping("SimulationsValuesById/{id}/")
    public String showSimulationsValuesForSimulation(@PathVariable("id") Long id,
                                                     @RequestParam(value = "page", defaultValue = "1") Integer page,
                                                     @RequestParam(value = "size", defaultValue = "5") Integer size,
                                                     Model model) {
        Page<SimulationsValues> ratePage = simulationService.pagination(id, PageRequest.of(page - 1, size));
        model.addAttribute("allP", ratePage);
        int totalPages = ratePage.getTotalPages();
        if (totalPages > 0) {
            List<Integer> pageNumbers = IntStream.rangeClosed(1, totalPages)
                    .boxed()
                    .collect(Collectors.toList());
            model.addAttribute("pageNumbers", pageNumbers);
        }
        model.addAttribute("s", simulationRepository.findAll());
        return "allSimsSimulationValues";
    }

分页方式

public Page<SimulationsValues> pagination(Long id, Pageable pageable) {
        int pageSize = pageable.getPageSize();
        int currentPage = pageable.getPageNumber();
        int startItem = currentPage * pageSize;
        List<SimulationsValues> list;
        if (eachRemainingDayService.getSimulations().stream().filter(e -> e.getId().equals(id))
                .collect(Collectors.toList()).get(0).getSimulationsValues().size() < startItem) {
            list = Collections.emptyList();
        } else {
            int toIndex = Math.min(startItem + pageSize, (simulationRepository.findAll().stream()
                    .filter(e -> e.getId().equals(id)).collect(Collectors.toList()).get(0)
                    .getSimulationsValues().size()));
            list = simulationRepository.findAll().stream()
                    .filter(e -> e.getId().equals(id)).collect(Collectors.toList()).get(0)
                    .getSimulationsValues().subList(startItem, toIndex);
        }
        return new PageImpl<>(list, PageRequest.of(currentPage, pageSize), simulationRepository.findAll()
                .stream().filter(e -> e.getId().equals(id)).collect(Collectors.toList()).get(0)
                .getSimulationsValues().size());
    }

嗨,我有一个问题。我有一个带分页的 table(那个 table 的值分布在 5 页上),这个 table 的 url 例如:http://localhost:8080 /SimulationsValuesById/2563/ 其中 2563 是路径变量和某个对象的 ID,我想在 table 中显示其字段,当我单击 [=30] 下的某个页码(这里是第 2 页)时=],我收到错误状态 400 并在控制台上显示错误:无法将类型 'java.lang.String' 的值转换为所需类型 'java.lang.Long';嵌套异常是 java.lang.NumberFormatException:对于输入字符串:“{id}”] 和 url 更改为 http://localhost:8080/SimulationsValuesById/%7Bid%7D/?size=5&page=2。为什么当我尝试进入某个页面时,id 会更改为某个字符串(此处为 %7Bid%7D)? (%7Bid%7D 在每一页上)我如何使这个路径变量不变,所以无论我进入哪个页面它都保持不变所以我得到 http://localhost:8080/SimulationsValuesById/2563/?size= 5&page=2 或 http://localhost:8080/SimulationsValuesById/1111/?size=5&page=2?提前致谢。

据我所知,您需要为 {id} 路径变量设置一个值,就像您为大小和页面所做的那样 (reference):

<div style="display: inline" th:if="${allP.totalPages > 0}" class="pagination"
     th:each="pageNumber : ${pageNumbers}">
    <a th:href="@{/SimulationsValuesById/{id}/(id=${someValue}, size=${allP.size}, page=${pageNumber})}"
       th:text=${pageNumber}
       th:class="${pageNumber==allP.number + 1} ? active"></a>
</div>

如果我理解正确的话,你的控制器中应该有两个独立的端点:

  • 一个用于分页,没有id。这将 return 当前页面的模拟列表:
@GetMapping("/simulations")
    public String showSimulations(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                  @RequestParam(value = "size", defaultValue = "5") Integer size,
                                  Model model) 
{
    // return a list of simulations for a given page
}

迭代模拟:

<div th:each="simulation : ${simulations}">
    <a th:href="@{/simulation/{id}(id = ${simulation.id})}">
        <span th:text="${simulation.name}"></span>
    </a>
</div>
  • 第二个用于获取特定模拟的信息
@GetMapping("/simulation/{id}")
    public String showSimulation(@PathVariable("id") int id, 
                                  Model model) 
{
    // return simulation details
}
 @GetMapping("SimulationsValuesById/{id}/")
    public String showSimulationsValuesForSimulation(@PathVariable("id") Long id,
                                                     @RequestParam(value = "page", defaultValue = "1") Integer page,
                                                     @RequestParam(value = "size", defaultValue = "5") Integer size,
                                                     Model model) {
        Page<SimulationsValues> ratePage = simulationService.pagination(id, PageRequest.of(page - 1, size));
        model.addAttribute("allP", ratePage);
        int totalPages = ratePage.getTotalPages();
        if (totalPages > 0) {
            List<Integer> pageNumbers = IntStream.rangeClosed(1, totalPages)
                    .boxed()
                    .collect(Collectors.toList());
            model.addAttribute("pageNumbers", pageNumbers);
        }
        model.addAttribute("idS", id);
        model.addAttribute("s", simulationRepository.findAll());
        return "allSimsSimulationValues";
    }
<div style="display: inline" th:if="${allP.totalPages > 0}" class="pagination"
     th:each="pageNumber : ${pageNumbers}">
    <a th:href="@{/SimulationsValuesById/{idS}/(idS=${idS}, size=${allP.size}, page=${pageNumber})}"
       th:text=${pageNumber}
       th:class="${pageNumber==allP.number + 1} ? active"></a>
</div>

我只是将 id 从 @PathVariable() 传递给 .html 作为 idS 并将其用作 url 的一部分,一切正常。