【发布时间】:2019-07-24 21:24:27
【问题描述】:
一段时间以来一直在纠结这个问题,试图让一个简单的下拉菜单工作。它填充有测试对象。这些 Test 对象存储在 List 中,List 包含在 TestController 对象中。 TestController 也有一个“activeTest”字段,这是我们要从下拉菜单中存储提交的测试的地方。它应该像这样工作:
1*从下拉菜单中选择一个测试对象 2*按提交 3*表单的POST方法应该把选中的Test对象通过.setActiveTest(test)添加为activeTest的当前值
我有几个重复出现的错误,但现在我有一个主要错误阻止我继续前进:
“bean name 'test' 的 BindingResult 和普通目标对象都不能用作请求属性”
我知道它与 HTML 视图中的第 15 行有关 (select 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 类,其中包含存储所有 Test 对象的 List:
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
}
【问题讨论】: