java - 我的复选框列表未填充相应的值

标签 java spring-mvc spring-boot checkbox thymeleaf

我在java端填充了2个数组列表: 一个包含 Nature 的完整列表:allNature,另一个包含 java 端 natures 上选定的列表。如何检查完整 allNatures 列表中的 natures

我在文档中读到“如果我们的 features 属性在表单支持 bean 中包含一些选定的值,th:field 会处理这个问题,并添加一个 check= “checked”属性到相应的输入标签。

但是 allNature 列表包含一些元素,并且未检查它们。

在此演变之前,naturesallNatures 是 String 元素,并且它曾经可以工作。现在我在 Nature 元素中更改它,它不再起作用。在这里,它是不同的对象引用。

这是我的 html 代码:

<div th:each="nature : ${allNature}" class="checkbox">
    <label > 
     <input type="checkbox" th:field="*{natures}" th:value="${nature}" class="checkboxNature" />
         <span th:text="${nature.nom}">...</span>
       <span th:text="${nature.routage.nomRoutage}" >...</span>
    </label>
</div>

以及我的 Controller 中的相关(对我来说)java代码:

@Controller
@SessionAttributes(value = "topologie", types = { Topologie.class })
@RequestMapping("/bus/topologie")
public class TopologieController {
    @ModelAttribute("allNature")
    public List<Nature> getAllNatures(final Topologie topologie)
            throws Exception {
        LOGGER.info("ModelAttribute to get all Nature for Cadre : {}",
                topologie.getCadre());
        return natureService.getNaturesByVersionCadre(topologie.getCadre(),
                topologie.getVersionCadre());
    }

和对象引用

public class Topologie {
    private List<Nature> natures = new ArrayList<Nature>();

在我的 Controller 中,在显示模板之前,此代码确认必须检查 allNature 列表中 6 个元素中的 3 个元素:

for (Nature nat : natSelect) {
    LOGGER.info(" nature : {}, contains: {}", nat.getNom(),
            allNature.contains(nat));
}

结果:

2017-12-05 12:11:45.450  INFO 6984 --- [nio-8990-exec-3] f.cnamts.navigo.web.TopologieController  :  nature : hi_atmplm2a_out, contains: true
2017-12-05 12:11:45.450  INFO 6984 --- [nio-8990-exec-3] f.cnamts.navigo.web.TopologieController  :  nature : hi_lm2aconv_in, contains: true
2017-12-05 12:11:45.450  INFO 6984 --- [nio-8990-exec-3] f.cnamts.navigo.web.TopologieController  :  nature : hi_lm2asign_out, contains: true

最佳答案

由于 Nature 是用户定义的数据类型,因此要使用 th:field 进行工作,您必须重写 bean 中的 equals 方法,以在比较对象时定义相等性。

关于java - 我的复选框列表未填充相应的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47577575/

相关文章:

java - 在 Java 中使用递归的 ConcurrentModificationException

Java 带开关

java - 一个普通的 servlet 可以被配置为一个 seam 组件吗?

java - 多模块JHipster应用程序

java - SpringBoot 2使用HikariCP无法连接MySQL

java - 二维数组列表的排列

java - REST 中成功的 DELETE 语句的 HTTP 状态返回码是什么?

java - Spring Tool Suite 启动错误 - Java 已启动但返回退出代码 =13

java - 部署到外部 Tomcat/tc 服务器实例时,Spring Boot MVC 应用程序返回 HTTP 404

java - Spring Boot 不绑定(bind)到 Tomcat 端口