java Thymeleaf下拉菜单故障
有一段时间以来,我一直在围绕这个问题,试图让一个简单的下拉菜单工作。它由测试对象填充。这些测试对象存储在一个列表中,该列表包含在TestController对象中。TestController还有一个“activeTest”字段,我们希望在该字段中存储下拉菜单中提交的测试。它应该是这样工作的:
1*从下拉菜单中选择测试对象 2*新闻稿提交 3*表单的POST方法应采用所选的测试对象,并通过将其添加为activeTest的当前值。setActiveTest(测试)
我有几个反复出现的错误,但现在我有一个主要的错误阻碍了我的进步:
“bean名称“test”的BindingResult或普通目标对象都不能作为请求属性使用”
我知道这与HTML视图中的第15行有关(选择th:field=“*{test}”),但我不知道如何解决它,也不知道它希望我修复什么
控制器:
@ComponentScan
@Controller
public class TeacherController {
TestController testcont = TestController.getInstance();
@RequestMapping(value = {"/sendTest"}, method = RequestMethod.GET)
public String currentTestOptions(Model model) {
model.addAttribute("test", new Test());
model.addAttribute("tests", testcont.showAllTests());
model.addAttribute("currentTest", testcont.getActiveTest());
return "sendTest";
}
@RequestMapping(value = {"/sendTest"}, method = RequestMethod.POST)
public String sendTest(@ModelAttribute("test") @Valid @RequestBody Test test){
testcont.SetActiveTest(test);
return "sendTest";
}
}
HTML:
<body>
<p>
<a href='/Teacher/NewTest'>New Test upload</a> <a href='/Teacher/TestResults'>See Test Results</a>
</p>
<form id="dropdown" th:action="@{/sendTest}" th:object="${test}" method='post'>
<label>Select test</label>
<select th:field="*{test}">
<option th:each="test : ${tests}"
value="${test}"
th:text="${test.name}"></option>
<input type='submit' value='Submit'>
</form>
<a> Current test for students: </a>
<p th:text="${activeTest}" ></p>
<div>
<a>Available tests for students:</a>
<th:block th:each="Test : ${tests}">
<tr>
<td th:text="${Test.getName()}">...</td>
<td th:text="${Test.getFile().getName()}">...</td>
</tr>
</div>
</body>
测试等级:
public class Test implements Serializable{
/**
*
*/
private static final long serialVersionUID = -8729209678450935222L;
private File file;
private String name;
private String question;
private String answer1;
private String answer2;
private double studentAnswer;
private List<Double> answers;
private List<Student> students;
public Test(File file, String name, String question, String answer1, String answer2) {
this.file = file;
this.name = name;
this.question = question;
this.answer1 = answer1;
this.answer2 = answer2;
answers= new ArrayList<>();
students = new ArrayList<>();
}
// Getters and setters for above fields.
}
TestController类,其中包含存储所有测试对象的列表:
public class TestController {
private static TestController instance = null;
private List<Test> tests;
private List<Student> students;
private Test active = null;
private TestController() {
tests = new ArrayList<>();
students = new ArrayList<>();
loadTests();
}
public static TestController getInstance() {
if (instance == null) {
instance = new TestController();
}
return instance;
}
public void SetActiveTest(Test test) {
active = test;
}
public Test getActiveTest() {
System.out.println(active);
return active;
}
public List<Test> showAllTests() {
return tests;
}
// Other methods
}
# 1 楼答案
阅读Thymeleaf Variable
在
Test()
类中没有测试字段