我是百里香的新手。我正在尝试创建简单的crud应用程序。我正在尝试删除删除按钮上的Customer类的对象。如何将参数(例如- id)设置为使用Thymeleaf调用deleteUser的方法。这是我的控制器。
package controllers;
//imports
@Controller
public class WebController extends WebMvcConfigurerAdapter {
@Autowired
private CustomerDAO customerDAO;
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/results").setViewName("results");
}
//show all users
@RequestMapping(value="/users", method=RequestMethod.GET)
public String contacts(Model model) {
model.addAttribute("users",customerDAO.findAll());
return "list";
}
//show form
@RequestMapping(value="/users/add", method=RequestMethod.GET)
public String showForm(Customer customer) {
return "form";
}
//add user
@RequestMapping(value="/users/doAdd", method=RequestMethod.POST)
public String addUser(@RequestParam("firstName") String firstName,
@RequestParam("lastName") String lastName,
@RequestParam("lastName") String email) {
customerDAO.save(new Customer(firstName, lastName, email));
return "redirect:/users";
}
//delete user
@RequestMapping(value="users/doDelete/{id}", method = RequestMethod.POST)
public String deleteUser (@PathVariable Long id) {
customerDAO.delete(id);
return "redirect:/users";
}
}
这是我的观点。
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Serving Web Content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
List of users
<a href="users/add">Add new user</a>
<table>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Action</th>
</tr>
<tr th:each="user : ${users}">
<td th:text="${user.id}">Id</td>
<td th:text="${user.firstName}">First name</td>
<td th:text="${user.lastName}">Last Name</td>
<td th:text="${user.email}">Email</td>
<td>
<form th:action="@{/users/doDelete/}" th:object="${customer}" method="post">
<button type="submit">Delete</button>
</form>
</td>
</tr>
</table>
</body>
</html>
发布于 2014-04-02 15:05:43
执行此操作不需要表单:
<td>
<a th:href="@{'/users/doDelete/' + ${user.id}}">
<span>Delete</span>
</a>
</td>
发布于 2014-04-03 20:55:34
Blejzer answer是一个简单而直接的解决方案,除非你还在使用spring安全(总是推荐),在这种情况下,你应该更喜欢POST而不是GET来进行所有的修改操作,比如delete,以防止CSRF攻击。这就是为什么spring recommends logout只能这样做的原因。为了适应POST,将您的控制器更改为从请求参数而不是路径变量读取此参数
//delete user
@RequestMapping(value="users/doDelete", method = RequestMethod.POST)
public String deleteUser (@RequestParam Long id) {
customerDAO.delete(id);
return "redirect:/users";
}
在表单中添加一个隐藏字段,该字段以id作为名称并在隐藏参数中显示它的值
<form th:action="@{/users/doDelete}" th:object="${customer}" method="post">
<input type="hidden" th:field="${id}" />
<button type="submit">Delete</button>
</form>
顺便说一句,即使你没有使用spring security,也总是推荐使用post来进行任何实体修改操作(比如删除或更新)。从长远来看,让你在网络上省去了很多麻烦。有关详细信息,请查看Quick Checklist for Choosing HTTP GET or POST。
发布于 2016-10-13 11:25:23
path变量可以设置为:
<a th:href="@{/users/doDelete/__${user.id}__}"><span>Delete</span></a>
https://stackoverflow.com/questions/22794057
复制相似问题