使用百里香叶自学Spring 5,SpringBoot和MVC。这是一个简单的应用程序。在移至数据访问层之前,我首先与控制器一起工作以正确填充视图。
我的问题是视图未填充我在Controller中创建的数据。
这是我的控制器:
// generates a logger class for you
@Slf4j
@Controller
@RequestMapping("/select")
public class AreaCodeController {
/*
* This method is called BEFORE the @GetMapping method.
* Building a list of items to display on the select template
*/
@ModelAttribute()
public void addAreaToModel(Model model) {
// id, code, country, abbr, provStateLongName, StateCode
List<Area> listing = Arrays.asList(new Area(1000, 123, "US", "AL", "Alabama", StateCode.AL),
new Area(1001, 124, "US", "MS", "Mississippi", StateCode.MS),
new Area(1002, 125, "US", "WA", "Washington", StateCode.WA),
new Area(1003, 126, "US", "WV", "West Virgina", StateCode.WV),
new Area(1004, 127, "US", "GA", "Georgia", StateCode.GA),
new Area(1005, 128, "US", "IL", "Illonis", StateCode.IL),
new Area(1006, 129, "US", "OR", "Oregon", StateCode.OR),
new Area(1007, 121, "US", "CA", "California", StateCode.CA),
new Area(1008, 122, "US", "NV", "Nevada", StateCode.NV),
new Area(1009, 120, "US", "NM", "New Mexico", StateCode.NM),
new Area(1010, 130, "US", "LA", "WildWilly", StateCode.LA));
StateCode[] stateCodes = Area.StateCode.values();
for (StateCode stateCode : stateCodes) {
model.addAttribute("areaCodeList", filterByStateCode(listing, stateCode));
}
}
@GetMapping
public String showSelectForm(Model model) {
model.addAttribute("select", new BusinessNumber());
return "select";
}
private List<Area> filterByStateCode(List<Area> listing, StateCode sc)
{
return listing.stream().filter(x -> x.getCode().equals(sc)).collect(Collectors.toList());
}
}
这是我的观点:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Virtual Business Number Listing</title>
<link rel="stylesheet" th:href="@{/styles.css}" />
</head>
<body>
<h1>List of Available Business Numbers</h1>
<img th:src="@{/images/phone.png}" style="width:200px;height:125px"/>
<form method="POST" th:object="${select}">
<div class="grid">
<div class="area-group" id="abbrs">
<h3>Choose Your Business Number:</h3>
<div th:each="area : ${areaCodeList}">
<input type="checkbox" name="areaCodeList" th:value="{area.id}" />
<span th:text="${area.code}">Area Code</span><br/>
</div>
</div>
<br/>
<input type="Submit" id="submitButton" th:value="Save">
</div>
</form>
</body>
</html>
这是我看到的行为:
任何建议将不胜感激。
谢谢
俄罗斯
答案 0 :(得分:1)
浏览完代码后,我解决了自己的错误。尽管很痛苦,但它涉及几件事:
答案 1 :(得分:0)
我认为您的表单标签不知道要从控制器执行哪个操作,因此您需要以这种方式添加它:
1-您认为:<form method="POST" th:object="${select}" *th:action="@{/something}"*>
2-在您的控制器中:在您的方法@GetMapping上方应为@PostMapping( value =“ / something” ),因为您的表单具有用于创建新对象选择的post方法