问候视图和结果视图是否指向同一对象?



在这里,我们的控制器可能会返回两个视图之一。 在这种情况下,这两个方法签名都包含模型模型映射和模型属性,视图是否共享对先前请求句柄加载的模型和模型属性的访问权限?

@Controller
public class GreetingController {
@GetMapping("/greeting")
public String greetingForm(Model model) {
model.addAttribute("greeting", new Greeting());
return "greeting";
}
@PostMapping("/greeting")
public String greetingSubmit(@ModelAttribute Greeting greeting) {
return "result";
}

}

它不指向同一个对象。

我假设您正在使用 https://spring.io/guides/gs/handling-form-submission/而且它的代码命名约定非常混乱。

请参阅以下测试代码。 我故意更改了URL,变量名称。

问候.java

public class Greeting {
private long id;
private String content;    
//... getters and setters
}

问候语2.java

//created for testing
public class Greeting2 {
private long id;
private String content;
//... getters and setters
} 

问候控制器.java

@Controller
public class GreetingController {
@GetMapping("/greeting") // greeting URL and GET request method
public String greetingForm(Model model) { 
//  th:object="${foo}" in template and thymeleaf
model.addAttribute("foo", new Greeting()); 
return "greeting_tmpl"; // src/main/resources/templates/greeting_tmpl.html
}
@PostMapping("/greeting_post")
public String greetingSubmit(@ModelAttribute Greeting2 bar) {
//I expected using bar variable in result_tmpl, but it used Greeting2(lowercase) as variable
return "result_tmpl"; // src/main/resources/templates/result_tmpl.html
}
}

src/main/resources/templates/greeting_tmpl.html

...
<body>
<h1>Form</h1>
<form action="#" th:action="@{/greeting_post}" th:object="${foo}" method="post">
<p>Id: <input type="text" th:field="*{id}" /></p>
<p>Message: <input type="text" th:field="*{content}" /></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</body>
</html>

src/main/resources/templates/result_tmpl.html

...
<body>
<h1>Result</h1>
<p th:text="'id: ' + ${greeting2.id}" /> <!-- this name should be like bar.id not greeting2 -->
<p th:text="'content: ' + ${greeting2.content}" />
<a href="/greeting">Submit another message</a>
</body>
</html>

只是

  1. 浏览器触发器@GetMapping。
  2. 服务器将问候语
  3. 模型解析为问候语模板中的 HTML 表单值,并响应浏览器。
  4. 使用 POST 方法触发器@PostMapping提交表单数据。
  5. @ModelAttribute Greeting2(可以是任何可以解析表单值的模型(在本例中为 id,content(会将表单值解析为 Greeting2 模型。
  6. 服务器将问候语
  7. 2 模型解析为问候语模板中的 HTML 表单值和对浏览器的响应。