在Spring boot Java的表单中使用另一个包中的模型
在我的builds.html
页面中,我有以下表格:
<div id="deployment">
<form action="#" th:action="@{/builds}" th:object="${build}" method="post">
<textarea rows="20" cols="150" th:field="*{configuration}">
</textarea>
<br></br>
<button class="btn btn-primary btn-cons" type="submit">Deploy</button>
</form>
</div>
我的BuildsControler.java
在deployments
包中:
import builds.Build;
@Controller
@ComponentScan("builds")
public class BuildsController {
// @Autowired
// private BuildsRepository buildsRepository;
private final static Logger logger = Logger.getLogger(BuildsController.class);
/*
* Add the builds url page
*/
@GetMapping("/builds")
public String index(Model model) {
model.addAttribute("builds", new Build());
return "builds";
}
/**
*
* @param object
* @return
*/
@PostMapping("/builds")
public Build deploy(@ModelAttribute Build build) {
logger.info(String.format("--------- Deploying build: %s --------", build));
return build;
}
}
当Build
模型在builds
包中时:
@Document(collection = "builds")
public class Build {
@Id
@JsonSerialize(using = ToStringSerializer.class)
private String id;
private String date;
@NotNull
private String configuration;
public Build() {
}
public Build(String configuration) {
this.id = new ObjectId().toHexString();
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
this.date = dateFormat.format(new Date());
this.configuration = configuration;
}
}
所以我得到了以下错误:
[THYMELEAF][http-nio-8080-exec-1] Exception processing template "builds": Exception evaluating SpringEL expression: "builds.build" (builds:514)
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "builds.build" (builds:514)] with root cause
org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 7): Property or field 'build' cannot be found on object of type 'builds.Build' - maybe not public?
既然Build
在另一个包中,我如何在表单中使用build
模型
# 1 楼答案
在GET方法中添加属性时,应该使用
build
而不是builds
,因为在这里使用build
th:object="${build}"
,所以Spring找不到它这个文件可能会有所帮助