![](/img/trans.png)
[英]Spring Thymeleaf - How do I find an object id from html and pass the id to the controller?
[英]How do I pass an object with thymeleaf to java spring controller?
如果沒有 object 是 null,我無法通過 object項目。 如何將 object 傳遞給 spring controller?
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Home</title>
</head>
<body>
<form action="/addproject" method="POST">
<input type="hidden" name="project" th:value="${project}"/>
<input type="submit" value="Save Project" class="submit">
</form>
</body>
</html>
@Controller
public class ProjectController {
@GetMapping("/")
public String indexPage(Model model) {
model.addAttribute("project", new Project("Test", "Test"));
return "index";
}
@PostMapping("/addproject")
public String add(WebRequest webRequest) {
Project p = (Project) webRequest.getAttribute("project", WebRequest.SCOPE_REQUEST);
return "index";
}
}
請檢查這篇文章。 簡而言之,您需要將所需的 object 傳遞給ModelAndView
,而不是Model
:
@GetMapping("/")
public ModelAndView indexPage(Model model) {
ModelAndView mav = new ModelAndView("index");
mav.addObject("project", new Project("Test", "Test"));
return mav;
}
並從模板中按名稱訪問它:
<b th:text="${project.attribute}">Text ...</b>
我建議您先在此處處理文檔。
與其他答案一樣,您對ModelAndView
沒有要求或問題。
第一次調用/project
頁面時,@GetMapping 會加載項目@GetMapping
信息,如果需要,在更改並提交時會被@PostMapping
捕獲。
add-project.html
文件:
<!DOCTYPE HTML>
<html xmlns:th="https://www.thymeleaf.org">
<head>
<title>Project Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Project Form</h1>
<form method="post" th:action="@{/project}" th:object="${project}">
<p>Name: <input type="text" th:field="*{name}" /></p>
<p>Description: <input type="text" th:field="*{description}" /></p>
<p><input type="submit" value="Submit" /> </p>
</form>
</body>
</html>
Project.java
文件:
public class Project {
private String name;
private String description;
public Project(String name, String description) {
this.name = name;
this.description = description;
}
// getter/setter ...
}
ProjectController.java
文件:
@Controller
public class ProjectController {
@GetMapping("/project")
public String greetingForm(Model model) {
model.addAttribute("project", new Project("PN1", "PD1"));
return "add-project";
}
@PostMapping("/project")
public String greetingSubmit(@ModelAttribute Project project, Model model) {
model.addAttribute("project", project);
return "add-project";
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.