什么是预期的
数据绑定后,网页应反映数据。
详细信息
控制器码
@Controller
@Configuration
@Component
public class Controller {
@Autowired
Credentials c;
@GetMapping("/greeting")
public String greetingForm(Model model) {
model.addAttribute("greeting", new RequestData());
return "greeting";
}
@PostMapping("/greeting")
public String greetingSubmit(@ModelAttribute RequestData greeting) {
if (c.getUserName().equals(greeting.getId()) && c.getPassword().equals(greeting.getContent()))
{
return "result";
}
else
{
return "error";
}
}
}RequestData.java
public class RequestData {
private String id;
private String content;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}Credentials.java
@Component
@Configuration
@PropertySource("classpath:application.properties")
public class Credentials {
public String userName;
public String password;
@Autowired
private Environment env;
@Autowired
public String getUserName() {
return env.getProperty("spring.username");
}
public void setUserName(String userName) {
this.userName = userName;
}
@Autowired
public String getPassword() {
return env.getProperty("spring.password");
}
public void setPassword(String password) {
this.password = password;
}
}result.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Hello World</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Hello World</h1>
<p th:text="'id: ' + ${greeting.id}" />
<p th:text="'content: ' + ${greeting.content}" />
<a href="/greeting">Submit another message</a>
</body>
</html>能够编译、打包代码库并构建jar。但是,当我运行jar文件时,会得到以下错误:
2018-10-31 15:36:34.259 ERROR 8220 --- [nio-8080-exec-4] o.a.c.c.C.[.[.[/].[disp
atcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context
with path [] threw exception [Request processing failed; nested exception is or
g.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringE
L expression: "greeting.id" (template: "result" - line 9, col 8)] with root caus
e
org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property o
r field 'id' cannot be found on null我不知道问题出在哪里,thymeleaf doc说,模型属性可以用${attributeName}访问,我也使用的是相同的,但是为什么它说"id无法找到“
请建议
发布于 2018-10-31 11:02:49
从Spring文档,我引用-
当未显式指定模型属性名称时会发生什么?在这种情况下,将根据模型属性的类型为其分配默认名称。例如,如果方法返回类型为Account的对象,则使用的默认名称是"account“。您可以通过@ModelAttribute注释的值来改变这一点。如果直接向模型添加属性,则使用适当的重载addAttribute(..)方法--即,有或没有属性名。
在你的情况下
@PostMapping("/greeting")
public String greetingSubmit(@ModelAttribute("greeting) RequestData greeting) {
..
}https://stackoverflow.com/questions/53081314
复制相似问题