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

4ioopgfo  于 9个月前  发布在  Spring
关注(0)|答案(2)|浏览(101)

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

public class Garage
List<Vehicule> vehicules;

...

public abstract class Vehicule
List<Wheel> wheels

...

public class Car extends Vehicule
public class Bike extends Vehicule

... 

public class Wheel
boolean damaged

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

<form id="garage"
      action="#"
      th:action="@{/save}"
      th:object="${garage}"
      method="post">
            <div th:each="vehicule, i : ${garage.getVehicules()}">
               <ul>
                  <li th:each="wheel, j : ${garage.getWheels()}">
                     <input type="checkbox" th:field="*{{vehicules[__${i.index}__].wheels}}" th:value="${wheel}" />
                    <label th:for="${#ids.next('wheels')}" th:text="${wheel.value}">Label</label>
                  </li>
               </ul>
            </div>
<input type="submit" value="Submit" /> <input type="reset" value="Reset" />
</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。
但我发现我原来的问题的解决方案与转换器配置类和模板中的隐藏输入:

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

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

相关问题