【发布时间】:2016-07-11 04:47:48
【问题描述】:
我知道这个问题对一些人来说可能听起来很愚蠢,但我是 Spring Boot 和 Thymeleaf 的新手。
假设我目前在page1.html。用户单击某个按钮,该按钮会向我的控制器 MyController.java 生成一个 POST/GET 请求,该请求使用 @RequestMapping 将此请求映射到某个函数。
处理完请求后,我会从控制器返回一个视图名称,例如 return "page2"。
page1.html 的内容 更改,但 url 仍然保持不变,如 http://localhost:8080/page1 而不是更改为 http://localhost:8080/page2
我知道要转到不同的页面,我必须使用 redirection,但为什么 view 无法做到这一点?
谁能解释一下为什么会发生这种情况,我应该什么时候使用重定向或什么时候应该使用视图?
编辑 1:
这是我的控制器
@RequestMapping (value = "edit", method = RequestMethod.POST, params="action=ADD")
{
public String saveUser(@ModelAttribute UserDto userDto) {
try {
User user = new User();
if(userDto.getId() != null) {
throw new UserExists();
}
user.setName(userDto.getName());
user.setEmail(userDto.getEmail());
System.err.println("Request Recieved");
userDao.save(user);
return "success";
} catch (Exception e) {
System.err.println("Error Saving User");
e.printStackTrace();
return "failure";
}
}
这是我的看法
<form id="manipulate-data-form" th:object="${userobj}" method="post" th:action="@{/edit}">
<table id="manipulate" class="table table-bordered">
<tr>
<td>ID</td>
<td><input type="text" class="form-control" th:if="${userobj != null}" th:field="*{id}" ></input></td>
</tr>
<tr>
<td>NAME</td>
<td><input type="text" class="form-control" th:if="${userobj != null}" th:field="*{name}" ></input></td>
</tr>
<tr>
<td>EMAIL</td>
<td><input type="text" class="form-control" th:if="${userobj != null}" th:field="*{email}" ></input></td>
</tr>
<tr>
<td><input name="action" value="ADD" type="submit" class="btn btn-success" ></input></td>
<td>
<input name="action" value="DELETE" type="submit" class="btn btn-danger" ></input>
<input style="margin-left: 30px" name="action" value="UPDATE" type="submit" class="btn btn-primary" ></input>
</td>
</tr>
</table>
</form>
所以基本上点击它调用 saveUser() 控制器的按钮,然后当我返回 failure 或 success 查看 URL 保持不变,但内容页面变化对应成功或失败。
【问题讨论】:
-
您的问题有什么更新吗?
-
@Patrick 抱歉无法早点回复。我出去了一会儿。但我已经在 EDIT 1 中添加了代码。
-
查看我编辑的答案。
标签: java spring view spring-boot thymeleaf