如何正确地将复选框绑定到百里香中的对象列表? [英] How to correctly bind checkbox to the object list in thymeleaf?

查看:80
本文介绍了如何正确地将复选框绑定到百里香中的对象列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的域模型由EmployeeCertificate组成.一名员工可以引用/拥有许多证书(一对多关系).证书的完整列表可以从certificateService获取.

My domain model consist of an Employee and Certificate. One Employee can reference/have many certificates (one-to-many relationship). The full list of certificates could be get from the certificateService.

要为员工分配一些特殊证书,我使用了百里香的th:checkbox元素,如下所示:

To assign some special certificate to the employee I used th:checkbox element from thymeleaf as follow:

<form action="#" th:action="@{/employee/add}" th:object="${employee}" method="post">
    <table>
        <tr>
            <td>Name</td>
            <td><input type="text" th:field="*{name}"></td>
        </tr>
        <tr>
            <td>Certificate</td>
            <td>
                <th:block th:each="certificate , stat : ${certificates}">
                    <input type="checkbox" th:field="*{certificates}" name="certificates" th:value="${certificate.id]}"/>
                    <label th:text="${certificate.name}" ></label>
                </th:block>
            </td>
        </tr>
        <tr>
            <td colspan="2"><input type="submit" value="Add"/></td>
        </tr>
    </table>
</form>

现在,当我尝试提交HTML表单时,总是出现以下错误:

Now when I'm trying to submit the HTML form I always get following error:

400-客户端发送的请求在语法上不正确.

400 - The request sent by the client was syntactically incorrect.

我的问题是:如何使用百里香叶将复选框元素正确绑定到对象列表?

My question is: How to correctly bind checkbox elements to the object list with thymeleaf?

控制器

@RequestMapping(value = "/add" , method = RequestMethod.GET)
public String add(Model model) {
    model.addAttribute("employee",new Employee());
    model.addAttribute("certificates",certificateService.getList());
    return "add";
}

@RequestMapping(value = "/add" , method = RequestMethod.POST)
public String addSave(@ModelAttribute("employee")Employee employee) {
    System.out.println(employee);
    return "list";
}

员工实体

@Entity
@Table(name = "employee")
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID")
    private int id;

    @Column(name = "Name")
    private String name;

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "emp_cert",
            joinColumns = {@JoinColumn(name = "employee_id")},
            inverseJoinColumns = {@JoinColumn(name = "certificate_id")})
    private List<Certificate> certificates;

    public Employee() {
        if (certificates == null)
            certificates = new ArrayList<>();
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Certificate> getCertificates() {
        return certificates;
    }

    public void setCertificates(List<Certificate> certificates) {
        this.certificates = certificates;
    }

    @Override
    public String toString() {
        return "Employee [id=" + id + ", name=" + name + "certificates size = " + certificates.size() + " ]";
    }
}

证书实体

@Entity
@Table(name = "certificate")
public class Certificate {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "Id")
    private int id;

    @Column(name = "name")
    private String name;

    @ManyToMany(mappedBy = "certificates")
    private List<Employee> employees;

    public Certificate() {
        if (employees == null)
            employees = new ArrayList<>();
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Employee> getEmployees() {
        return employees;
    }

    public void setEmployees(List<Employee> employees) {
        this.employees = employees;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + id;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Certificate other = (Certificate) obj;
        if (id != other.id)
            return false;
        return true;
    }
}

推荐答案

我使用了自定义解决方案来解决此问题,我通过发送证书数组来实现了该解决方案控制器的ID,并以 requestParam 的形式收到.需求更改在下面定义.

I used a custom solution to solve this issue, i implemented it by sending an array of certificates id to controller and received it as requestParam . The require changes are defined below .

查看

         <tr>
             <td>Certificate</td>
             <td>
               <th:block th:each="certificate : ${certificates}">
                <input type="checkbox" name="cers" th:value="${certificate.id}"/>
                 <label th:text="${certificate.name}"></label>
               </th:block>
             </td>
           </tr>

控制器

@RequestMapping(value = "/add" , method = RequestMethod.POST)
public String addSave(
         @ModelAttribute("employee")Employee employee , 
         @RequestParam(value = "cers" , required = false) int[] cers ,
         BindingResult bindingResult , Model model) {

if(cers != null) {
    Certificate certificate = null ;
    for (int i = 0; i < cers.length; i++) {

        if(certificateService.isFound(cers[i])) {
            certificate = new  Certificate();
            certificate.setId(cers[i]);
          employee.getCertificates().add(certificate);  
        }
    }
        for (int i = 0; i < employee.getCertificates().size(); i++) {
            System.out.println(employee.getCertificates().get(i));
        }
}

这篇关于如何正确地将复选框绑定到百里香中的对象列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆