我有一个表单,用户在其中创建新考试,并在表单中用户从下拉菜单中选择一个主题。该下拉列表包含主题字符串,而不是实际的主题对象。在我的程序中,存在与考试具有一对多关系的实际主题对象。
如何找到用户选择的值?我想将其添加到模型中,以便我可以创建一个检查对象并将其添加到数据库中。
将用户选择的主题字符串添加到模型后如何
我找到用户选择的值吗?
因为我想将他们选择的内容设置为等于主题名称,然后搜索
具有相同名称的主题的主题存储库,以便考试
可以添加到该主题。
希望我的代码能让这一点更加清晰。
我收到这个错误。 Bindingresult 和 bean 名称主题的普通目标对象都不能用作请求属性。
这是我的控制器的代码
@GetMapping("/addexam")
public String showExamForm(Model model) {
// Here I am finding the subjects that belong to the current user
//and adding them as strings to an arraylist.
//I populate the dropdown with strings fromthis arraylist.
Authentication loggedInUser = SecurityContextHolder.getContext().getAuthentication();
String email = loggedInUser.getName();
User user = userRepository.findByEmailAddress(email);
ArrayList<String> subjects = new ArrayList<String>();
for(Subject sub:user.getSubject())
{
subjects.add(sub.getSubjectName());
}
model.addAttribute("subjects", subjects);
return "addExam";
}
@PostMapping("/addexam")
public String addNewExam(@ModelAttribute("exam") @Valid @RequestBody Exam
exam,UserRegistrationDto userDto, BindingResult result, Model model) {
examRepository.save(exam);
model.addAttribute("examTitle", exam.getExamTitle());
model.addAttribute("examGradeWorth", exam.getExamGradeWorth());
model.addAttribute("subject", exam.getSubject());
//I want to find the user selected value and set it to equal
//subjectname:
String subjectName =;
//Here I will search the subjectRepository for the subjectName and set subject to equal the subject that was found.
Subject subject = subjectRepository.findBySubjectName(subjectName);
//then exam will be added to that subject as subject has a one to many relationship with exam.
subject.addExam(exam);
subjectRepository.save(subject);
return "userProfile1";
}
}
这是html。
<form action="#" th:action="@{/addExam}" th:object="${exam}"
method="post">
<div th:object="${subject}">
<select th:field="*{subject}" class="form-control" id="subject"
name= "subject">
<option value="">Select subject</option>
<option
th:each="Subject : ${subjects}"
th:value="${Subject}"
th:text="${Subject}"></option>
</div>
<div>
<table>
<tr>
<td><input type="text" th:field="*{examTitle}" /></td>
</tr>
<tr>
<td> Exam grade worth </td>
<td><input th:field="*{examGradeWorth}" /></td>
</tr>