@Controller
@RequestMapping("/")
@RequiredArgsConstructor
public class IndexController {
private final SkillService skillService;
@GetMapping("/manager-profile")
public String managerProfile(Model model) {
model.addAttribute("skillList", skillService.findAllSkills());
return "manager-profile";
}
}
在视图本身中i遍历列表,并从那里创建选项。
<form th:action="@{/getEmployeeBySkill}" method="post" id="skill-form">
<div class="select-box manager">
<select class="select_box manager" id="select-skill" name="skill">
<option value="">Select</option>
<option th:each="skill : ${skillList}" th:attr="data-category=${skill.category}" th:value="${skill}" th:name="skill" th:text="${skill.title}"></option>
</select>
<input type="number" class="form-control" id="experience" placeholder="Experience">
<button type="submit" class="btn manager-select_box">Search</button>
</div>
</form>
我想将技能对象发送回另一个控制器的选择。
@Controller
@RequestMapping("/")
public class EmployeeController {
private final EmployeeService employeeService;
@PostMapping("/getEmployeeBySkill")
String getEmployeesBySkill (Model model, @ModelAttribute("skill") Skill skill) {
// do stuff
return "candidate-list";
}
}
,但是,我收到错误消息
There was an unexpected error (type=Bad Request, status=400).
Failed to convert value of type 'java.lang.String' to required type 'com.neusta.domain.Skill'; Failed to convert from type [java.lang.String] to type [java.lang.Long] for value 'com.neusta.domain.Skill@bb0c873'
org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'com.neusta.domain.Skill'; Failed to convert from type [java.lang.String] to type [java.lang.Long] for value 'com.neusta.domain.Skill@bb0c873'
没有人知道为什么?不可能通过百里叶(或html)“发送对象”。
问题是属性
th:value="${skill}"
。如果您查看生成的HTML(浏览器中页面的“查看源”)或查看错误消息的末尾,则会发现属性值为
com.neusta.domain.Skill@bb0c873
(或类似)。这是类的
toString()
${skill}
,因为HTML属性无法容纳对象,而只是一个字符串,这是系统的唯一字符串表示。而且该字符串表示不能“转换”回对象。
如果您读取错误消息,您会注意到Spring正在尝试将该值转换为Long
。那是因为它期望它的字符串表示形式,即can
转换回一个实体实例,即数据库ID,即是一个
Skill
,因此属性应为:
Long