如果物件不為空,我無法傳遞物件Project。如何將物件從 html 傳遞給 spring 控制器?
<!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";
}
}
uj5u.com熱心網友回復:
請檢查這篇文章。簡而言之,您需要將所需的物件傳遞給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>
uj5u.com熱心網友回復:
我建議您先處理此處的檔案。
您對ModelAndView.
第一次呼叫/project頁面時,專案類資訊會被加載@GetMapping,如果需要,會@PostMapping在你更改并提交時捕獲。
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 "project";
}
@PostMapping("/project")
public String greetingSubmit(@ModelAttribute Project project, Model model) {
model.addAttribute("project", project);
return "project";
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/373351.html
