java - Spring Boot 中使用 Thymeleaf 的下拉列表

标签 java spring-boot thymeleaf

我正在尝试在 Springboot 中使用 ArrayList 加载下拉列表,因为我是 springboot 的新手。

我已经尝试过,但没有按预期工作。

请找到我尝试过的代码如下:

Java 代码:

@Controller
public class DemoController {

@GetMapping("/create")
     public String create(Model model) {

      model.addAttribute("create", new Demo());

      return "create";

     }

     public void countriesList(Model model) {

          List<String> countryList = new ArrayList<>();

          countryList.add("US");
          countryList.add("UK");

          model.addAttribute("countries", countryList);

       }
}

HTML:

<form action="#" th:action="@{/create}" th:object="${create}" method="post">

        <select th:field="*{country}">
             <option value=""> -- </option>
             <option th:each="country : ${countries}" th:value="${country}" th:text="${country}"></option>
        </select>
</form>

最终没有错误,但仅使用 -- 加载到下拉列表中,而不加载国家/地区。

请帮我解决这个问题。

最佳答案

您从未调用过将国家/地区添加到模型中的函数...

@Controller
public class DemoController {

 @GetMapping("/create")
 public String create(Model model) {

  model.addAttribute("create", new Demo());
  countriesList(model); // this line is needed
  return "create";

 }

 private void countriesList(Model model) {

  List < String > countryList = new ArrayList < > ();

  countryList.add("US");
  countryList.add("UK");

  model.addAttribute("countries", countryList);

 }
}

关于java - Spring Boot 中使用 Thymeleaf 的下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56016414/

相关文章:

java - 具有两个包装器元素的 Jackson XML ArrayList 输出

spring-boot - 事务发件箱模式与微服务中的 ChainedKafkaTransactionManager

javascript - Thymeleaf 布局 : javascript

java - Webflux Reactive 对象在渲染 Thymeleaf View 之前未解析

java.lang.NoClassDefFoundError : Failed resolution of: Lcom/google/gson/Gson; 错误

java - App Engine 和云存储如何以编程方式保存具有公共(public)链接权限的文件

java - 在 pmd 中排除不起作用

java - 无法渲染jsp页面

java - 并行请求的 NullPointer 异常

Jquery Ajax 表单未提交且 url 显示 csrf token