我有一个实体类,其字段类型为org.bson.Document
。这些是我不允许修改的值,但是当使用 Spring Data 时,我需要将它们映射到我的模型类中,以便在将文档保存回 Mongo 后这些值不会丢失。因此,文档是从 Mongo 获取的,映射到 User POJO,然后传递到 Thymeleaf 表单。当我尝试将 Thymeleaf 表单发送回 Controller 时,我收到 400 Bad Request“对象验证失败...”错误,我知道这是因为这两个附加的 Document
字段。如何将这些字段传递给 Thymeleaf,然后返回 Controller ?它们不会在表单中修改,只是显示为隐藏输入:
<input id="resetPassword" th:field="${user.resetPassword}" type="hidden"/>
<input id="consents" th:field="${user.consents}" type="hidden"/>
还有我的User
类:
@Data
@Document(collection = "users")
@NoArgsConstructor
public class User {
@Id
private ObjectId id;
private String email;
private String name;
private String surname;
private String phone;
private String password;
private String country;
private SecurityLevel securityLevel = SecurityLevel.LOW;
private Timestamp created = Timestamp.from(Instant.now());
private Boolean blocked = false;
private org.bson.Document resetPassword;
private org.bson.Document consents;
}
最佳答案
听起来该对象已成功注入(inject) Thymeleaf 模板,但返回表单时在 Spring 中未正确解析。
您应该检查网页中的表示形式(需要 json?),然后确保您在 Spring 中定义了一个可以成功反序列化返回对象的处理程序。
如果 Document 类型没有传统的构造函数(无参数或全参数),或者某些字段是“隐藏”的(没有标准的 getXxx 和 setXxx 方法),那么当表单在没有自定义处理程序的情况下提交时,Spring 将无法重建对象。
同样,如果对象的所有字段(和子字段)没有 getter,Thymeleaf 模板将嵌入不完整的对象,从而无法正确上传。
查看此博文以获取更多信息:https://www.rainerhahnekamp.com/en/spring-mvc-json-serialization/
关于java - Thymeleaf 表单无法处理 org.bson.Document 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50509192/