如何使用构建器模式通过表单创建对象?

带有嵌套构建器的实体:

for(var i = 0; i < 100; i++){
    document.getElementById(rando(["Rock","Paper","Scissors","Lizard","Spock"]).value).click()
}

我知道如何使用main方法创建带有构建器模式的新对象,即

食品=新的Food.FoodBuilder ... setters ... build()

但是当我通过前端的表单向api提交信息时,我一直找不到如何使用此模式创建对象的方法。

fybbbg 回答:如何使用构建器模式通过表单创建对象?

我将假设您的api调用正在发送序列化的Food对象,然后该对象将被控制器接收。如果您尝试通过专门使用给定的构建器将这些数据反序列化为实例,则jackson应该能够通过提供JsonDeserialize参数通过builder注释为您完成此操作。

,

如果您使用JSP设计了前端,请通过导入spring form taglib使用spring form标签。 在控制器级别,您可以使用@ModelAttribute获得Whole对象。 只有在所有POJO都需要站立时,Spring才会处理嵌套对象。

,

工作代码(添加了@ JsonDeserialize,@ JsonPOJOBuilder,@ JsonCreator和@JsonProperty):

@Entity
@Table(name="food")
@JsonDeserialize(builder = Food.FoodBuilder.class)
public class Food {

    @Id
    @Column(name="id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private long id;

    @Column(name="name")
    private String name;

    @Column(name="type")
    private String type;

    @Column(name="description")
    private String description;

    @Column(name="date")
    private LocalDate expiration;

    @ManyToOne
    @JoinColumn(name="container_id",foreignKey = @ForeignKey(name = "FK_FOOD"))
    private Container container;

    private Food(FoodBuilder foodbuilder) {
        this.name = foodbuilder.name;
        this.type = foodbuilder.type;
        this.description = foodbuilder.description;
        this.expiration = foodbuilder.expiration;
    }

    //getters omitted for brevity

    @JsonPOJOBuilder(buildMethodName = "build",withPrefix = "set")
    public static class FoodBuilder {
        private String name;    
        private String type;
        private String description;
        private LocalDate expiration;

        @JsonCreator(mode = JsonCreator.Mode.DELEGATING)
        public FoodBuilder(@JsonProperty("name") String name) {
            this.name = name;
        }

        public FoodBuilder setType(String type) {
            this.type = type;
            return this;
        }

        public FoodBuilder setDescription(String description) {
            this.description = description;
            return this;
        }

        public FoodBuilder setExpiration(LocalDate expiration) {
            this.expiration = expiration;
            return this;
        }

        public Food buildFood(){
            return new Food(this);
        }
    }
}
本文链接:https://www.f2er.com/2980701.html

大家都在问