Spring Boot 使用thymeleaf将对象从html选择选项发送到控制器

ddrv8njm  于 2023-03-29  发布在  Spring
关注(0)|答案(1)|浏览(166)

我想用thymeleaf把一个对象从select发送到我的控制器。这是model类

@Entity
@Table(name = "Skills")
@Builder
public class Skill {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "id", nullable = false)
        private Long id;

        @Column(name = "title", nullable = false, length = 40)
        private String title;

        @Column(name = "category", nullable = false, length = 30)
        @Enumerated(EnumType.STRING)
        private Category category;
}

我正在向视图中添加技能列表

@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";
        }
}

在视图本身中,我遍历列表并从那里创建选项。

<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'

有人知道为什么吗?

r1wp621o

r1wp621o1#

通过Thymeleaf(或HTML)“发送对象”是不可能的。
问题是属性th:value="${skill}"。(浏览器中页面的“查看源代码”),或者查看错误消息的结尾,您将看到属性值为com.neusta.domain.Skill@bb0c873(或simular)。这是类的toString()方法的默认结果,用于呈现${skill},因为HTML属性不能保存对象,只能保存字符串,而这是系统所知道的唯一的字符串表示形式。而且这个字符串表示形式不能被“转换”回对象。
如果你阅读了错误消息,你会注意到Spring ist试图将该值转换为Long。这是因为它期望一个String表示,它可以转换回Skill实体示例,即数据库ID,这是一个Long,所以属性应该是:th:value="${skill.id}"

相关问题