通过百里香的url将id从视图发送到控制器

时间:2017-03-03 13:55:04

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

我想通过其ID在我的Spring-Boot应用程序中找到一个用户。 Controller方法是:

@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}”...)

1 个答案:

答案 0 :(得分:1)

您可以指定表单actiondoc):

  

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

     

<a th:href="@{/order/{id}/details(id=3,action='show_all')}">

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

<form th:action="@{/finduser/{id}(id=${user.id})}">

或者如果您希望在变量中包含url:

<form th:action="@{{finduser}/{id}(finduser=${finduser},id=${user.id})}">