【问题标题】:post id from view to controller through the url in thymeleaf通过 thymeleaf 中的 url 从视图发布 id 到控制器
【发布时间】:2017-07-23 16:11:34
【问题描述】:

我想通过 ID 在我的 Spring-Boot 应用程序中查找用户。 控制器方法是:

@RequestMapping(value = "finduser/{id}", method = RequestMethod.GET)
public User get(@PathVariable Long id) throws NotFoundException {
    log.info("Invoked method: get with ID: " + id);
    log.warn("Searching for user with ID " + id);
    User findOne = userRepository.findOne(id);
    if (findOne == null){
        log.error("Unexpected error, User with ID " + id + " not found");
        throw new NotFoundException("User with ID " + id + " not found");
    }
    log.info("User found. Sending request back. ID of user is " + id);
    return findOne;
}

我的 finduser.html 的正文是:

<body>

<h1>Find User:</h1>
<form th:object="${user}" th:action="@{finduser}"  method="post">
    <p>Find by ID: <input type="text" th:field="*{id}" /></p>
    <p><input type="submit" value="Submit" /></p>
</form>

</body>

我应该改变什么以将 id 从视图传递到我的控制器,以便我的控制器可以使用 id 并搜索用户?

我认为id必须通过url传递,因为

@RequestMapping(value = "finduser/{id}"...)

【问题讨论】:

    标签: spring-mvc model-view-controller spring-boot thymeleaf


    【解决方案1】:

    你可以指定action(doc)的形式:

    还可以包含路径变量形式的参数 类似于普通参数,但在内部指定一个占位符 您的网址路径:

    &lt;a th:href="@{/order/{id}/details(id=3,action='show_all')}"&gt;

    在你的情况下,你可以这样做,例如:

    &lt;form th:action="@{/finduser/{id}(id=${user.id})}"&gt;

    或者如果您更喜欢将 url 放在变量中:

    &lt;form th:action="@{{finduser}/{id}(finduser=${finduser},id=${user.id})}"&gt;

    【讨论】:

      猜你喜欢
      • 2017-01-17
      • 2019-05-20
      • 2021-02-09
      • 1970-01-01
      • 2015-12-23
      • 2016-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多