正如标题所述,我想知道如何在该项目中实现该功能。我是这个春季和Thymeleaf主题的新手,它使用CrudRepository,实体,每个存储库的服务及其控制器。
在简历中,我要通过国家选择框的选定值填充地区选择框,并保留第一个国家选择框的选定值。
以下是代码段:
LocationController.java:
@Controller
public class LocationController {
@Autowired
private NationService nationService;
@Autowired
private DistrictService districtService;
@GetMapping("/location")
public String init(Model model){
model.addAttribute("nations", nationService.findAll());
return "location";
}
@PostMapping("/setDistricts")
public String setDistricts(Model model, @RequestParam long id){
model.addAttribute("districts", districtService.findAllByNation(id));
return "location";
};
}
Nation.java :(实体)
@Entity
public class Nation {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name = "nation")
private String nation;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getNation() {
return nation;
}
public void setNation(String nation) {
this.nation = nation;
}
}
District.java :(实体)
@Entity
public class District {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name = "district")
private String district;
@ManyToOne
private Nation nation;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public Nation getNation() {
return nation;
}
public void setNation(Nation nation) {
this.nation = nation;
}
}
location.html:
<div class="form-group">
<label for="nation"></label>
<select class="custom-select" id="nation">
<th:block th:each="nation: ${nations}" th:onchange="@{/setDistricts(id=${nation.id})}">
<option th:value="${nation.id}" th:text="${nation.nation}"></option>
</th:block>
</select>
</div>
感谢您的关注