cybertextron cybertextron - 2 months ago 21
Java Question

Using models from another package in forms in Spring boot - Java

In my

builds.html
page I have the following form:

<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>


my
BuildsControler.java
is in the
deployments
package:

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;
}


}

while the
Build
model is in the
builds
package:

@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;
}
}


So I'm getting the following error:

[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?


How can I use the
build
model in the form, since
Build
is in another package?

Answer

You should use build not builds, when adding an attribute in the GET method, because you use build here th:object="${build}", so Spring can't find it.

model.addAttribute("build", new Build());

This doc example may help.