spring 如何使用抽象类从Thymeleaf模板到Sping Boot 控制器?

4ioopgfo  于 2024-01-05  发布在  Spring
关注(0)|答案(2)|浏览(142)

我的应用程序有这样的结构模型:

  1. public class Garage
  2. List<Vehicule> vehicules;
  3. ...
  4. public abstract class Vehicule
  5. List<Wheel> wheels
  6. ...
  7. public class Car extends Vehicule
  8. public class Bike extends Vehicule
  9. ...
  10. public class Wheel
  11. boolean damaged

字符串
我有一个表格,其中包含一个复选框输入,让他知道如果车轮损坏:

  1. <form id="garage"
  2. action="#"
  3. th:action="@{/save}"
  4. th:object="${garage}"
  5. method="post">
  6. <div th:each="vehicule, i : ${garage.getVehicules()}">
  7. <ul>
  8. <li th:each="wheel, j : ${garage.getWheels()}">
  9. <input type="checkbox" th:field="*{{vehicules[__${i.index}__].wheels}}" th:value="${wheel}" />
  10. <label th:for="${#ids.next('wheels')}" th:text="${wheel.value}">Label</label>
  11. </li>
  12. </ul>
  13. </div>
  14. <input type="submit" value="Submit" /> <input type="reset" value="Reset" />
  15. </form>


我得到的是这个错误,因为我的车辆类上的抽象关键字:
java.lang.InstantiationException:null at java.base/jdk.internal.reflect. InstantiationExceptionConstructorImpl.newInstance(InstantiationExceptionConstructorImpl. java:48)~[na:na] at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:502)~[na:na] at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:486)~[na:na] at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils. java:197)
最后一点,这不是我的真实的代码,但它为您提供了最相似的问题上下文。

6l7fqoea

6l7fqoea1#

这意味着很明显,你处理抽象不恰当。你总是可以使用/创建数据传输对象作为中间人来处理你的数据到thymeleaf表单和从thymeleaf表单。

mm5n2pyu

mm5n2pyu2#

好吧,正如Alfred所说,我现在使用DTO。
但我发现我原来的问题的解决方案与转换器配置类和模板中的隐藏输入:

  1. <input type="hidden" th:field="*{vehicules[__${i.index}__]}" />
  1. public class VehiculeConverter implements Converter<String, Vehicule> {
  2. @Override
  3. public Vehicule convert(String source) {
  4. // return Car or Bike
  5. }
  6. }
  1. @Configuration
  2. public class FormattersConfig implements WebMvcConfigurer {
  3. @Override
  4. public void addFormatters(FormatterRegistry registry) {
  5. registry.addConverter(new VehiculeConverter());
  6. }
  7. }

我所理解的是,在模板中,隐藏字段调用转换器,因为控制器需要从String创建Vehicule对象。它甚至可以使用抽象关键字。

展开查看全部

相关问题