【问题标题】:Thymeleaf .html passing parameter to MVC Spring Controller JavaThymeleaf .html 将参数传递给 MVC Spring Controller Java
【发布时间】:2016-03-26 02:15:48
【问题描述】:

我是 thymeleaf 和 Spring 的新手——我正在为我的学校班级做一些小项目,但我的 html 链接有问题。我现在遇到了 2 个小时的麻烦,我用 10 种不同的方式编辑我的代码,所以请回答如何正确地做到这一点。下面是我的 html 模板(我在这里尝试使用 th:href 有两种不同的方式:

<table>
                <th>Name</th>
                <th>Date</th>
                <th>See</th>
                <th>Edit</th>
                <a th:each=" i : ${workouts}"  varStatus="status">
                <tr>
                    <td><a th:text="${i.getName()}"/></td>
                    <td><a th:text="${i.getDate()}"/></td>
                    <td><a href="seeWorktoutPage.html" th:href="@{'/seeWorkoutPage/'${i.getId()}}">See</a></td>
                    <td><a href="seeWorktoutPage.html" th:href="@{seeWorkoutPage(id=${i.getId()})}">See</a></td>                    </tr>
                </a>
            </table>

这是我的控制器: @控制器 公共类 SeeWorkoutController {

@RequestMapping(value = "/seeWorkoutPage/{id}", method=RequestMethod.GET, params="id")
public String test2(@PathVariable("id")Long id, Model model) {
        System.out.println(id);
        return "workoutsPage";
    }

但它现在可以正常工作。请帮忙。

【问题讨论】:

    标签: java html spring spring-mvc thymeleaf


    【解决方案1】:

    查看Thymeleaf Link URLs 的文档。特别是这个例子:

    <!-- Will produce '/gtvg/order/3/details' (plus rewriting) -->
    <a href="details.html" th:href="@{/order/{orderId}/details(orderId=${o.id})}">view</a>
    

    我想你的第二个例子差不多到了,但它应该是

    th:href="@{/seeWorkoutPage/{workoutId}(workoutId=${i.getId()})}"
    

    注意你如何指定{workoutId} 参数,然后在括号中给出它的值。

    【讨论】:

    • 好的,现在可以了。但是现在告诉我我应该如何回到另一个 html 页面?当我返回“myAnotherPageName”或返回“redirect:myAnotherPageName”时,我得到:无法将“java.lang.String”类型的值转换为所需的“java.lang.Long”类型;嵌套异常是 java.lang.NumberFormatException:对于输入字符串:“goToWorkoutsPage” 我希望我的链接看起来像:localhost:8080/goToWorkoutsPage 但我的是:localhost:8080/seeWorkoutPage/goToWorkoutsPage
    【解决方案2】:

    试试:

    <span th:each="workout: ${workouts}">
        <td><a th:text="${workout.name}"/></td>
        <td><a th:text="${#dates.format(workout.date,'MMM d, yyyy')}</td>
        <!-- add other stuff when you have the above working -->
    </span>
    

    您不需要get() 语法(它可能会在某些容器中引发异常)。此外,您似乎也在嵌套锚 (&lt;a&gt;) 标签。

    【讨论】:

      猜你喜欢
      • 2018-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-02
      • 2018-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多