How to correctly bind checkbox to the object list in thymeleaf?

Al-Mustafa Azhari

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.

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>

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

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?

Controller

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

Employee Entity

@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() + " ]";
    }
}

Certificate Entity

@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;
    }
}
Al-Mustafa Azhari

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 .

View

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

Controller

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

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

ThymeleafがList <Object>ではなくString配列を返す

Thymeleaf Without Object Classes?

Thymeleaf returning a String array instead of List<Object>

How to correctly mock an ObjectMapper object

How to correctly mock an ObjectMapper object

How to iterate list of objects in spring thymeleaf

Thymeleaf - Checked attribute of checkbox is not set in th:each OR how to properly restore a list of checkboxes some of which were previously checked

How to correctly delete an object from an array by name?

Vue - how to bind table column to a data object?

Checkbox check all is not working correctly

How to change php code to bind the parameters correctly for inserting multiple instances into mysql table

How to correctly deallocate a list of pointer to pair?

thymeleaf and condition and list size

How Do I Correctly Set a getElementById Object?

How to check stateChanged in a dynamic checkbox list in PyQt4

How to filter an object array using checkbox with angular?

How can I Bind a Custom Table Header to the Data correctly in Quasar / Vue

How do I filter a list sorted from Checkbox Values in Angular?

How to bind an entity object on a Detail page

How to bind nested list to datagridview in winforms

Passing an object into a Thymeleaf fragment

How to bind data object

how to create custom contact list with checkbox

How to bind new list via Html

Drupal Content Type: how to add a checkbox that hides an object if checked?

How to bind a combobox with converter to a list in WPF

How to bind control to object property?

List<? super List<? super Integer>> and List<? extends List<? super Integer>> and how to use it correctly?

How to create a list of clickable items using Thymeleaf

TOP 一覧

  1. 1

    Oracle11gクライアントを使用したOracle19Cサーバーへの接続

  2. 2

    Ansibleで複数行のシェルスクリプトを実行する方法

  3. 3

    Reactでclsxを使用する方法

  4. 4

    Python / SciPyのピーク検出アルゴリズム

  5. 5

    小さいデータセットサイズと大きいデータセットサイズを使用するMPI_Gatherを使用したMPI_Barrier?

  6. 6

    フィルタスライダーで複数の範囲を選択します-Tableau

  7. 7

    MariaDBによるデータベースの破損:テーブルがエンジンに存在しません

  8. 8

    複数の条件でループを構築する

  9. 9

    Google Cloud Storage から単一ページの React アプリを提供する

  10. 10

    Hide textOutput() when un-click row of a DT::datatable in shiny app

  11. 11

    JavaのREST APIの認証、JWTとベストプラクティス

  12. 12

    Angular 9 TypeError:未定義のプロパティ「subscribe」を読み取れません

  13. 13

    JavaからのMATLAB関数によりランタイムエラーが発生する(EXCEPTION_ACCESS_VIOLATION)

  14. 14

    Eclipseに既存のJavaプロジェクトをインポートしますが、JFrameのデザインビューが存在しませんか?

  15. 15

    Openlayers 3 : Interaction DragBox が機能しない

  16. 16

    print( "\ 0007")がビープ音を鳴らさないのはなぜですか?

  17. 17

    なぜArrays.copyOfは2倍高速System.arraycopyのより小さなアレイ用のでしょうか?

  18. 18

    App Engineクイックスタートから「helloworld.go」をアンデプロイし、代わりにバケット内のhtmlをポイントするにはどうすればよいですか?

  19. 19

    LaravelはDB接続を自動的に閉じますか?

  20. 20

    グラフ(.PNG)ファイルをエクスポートするZabbix

  21. 21

    Eclipseエラー:ビルドパスが不完全であると表示されます

ホットタグ

アーカイブ