我有一个类型为org.bson.Document
的字段的实体类。这些是我不允许修改的值,但是当使用Spring Data时,我需要在我的模型类中映射它们,以便在将文档保存回Mongo之后,这些值不会丢失。因此,文档从Mongo获取,映射到User
POJO,然后传递给Thymeleaf表单。当我尝试将Thymeleaf表单发送回控制器时,我得到400错误请求“验证对象失败...”错误,我知道这是因为这两个额外的Document
字段。我怎样才能将这些字段传递给Thymeleaf然后再回到控制器?它们不会在表单中修改,只显示为隐藏的输入:
<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;
}
答案 0 :(得分:0)
听起来好像该对象已成功注入Thymeleaf模板,但在返回表单时未在Spring中正确解析。
您应该检查网页中的表示(期望json?),然后确保您在Spring中定义了一个可以成功反序列化返回对象的处理程序。
如果Document类型没有传统的构造函数(no-args或all-args),或者某些字段被隐藏&#39; (没有标准的getXxx和setXxx方法),当没有自定义处理程序提交表单时,Spring将无法重建对象。
同样,如果对象的所有字段(和子字段)都没有getter,Thymeleaf模板将嵌入一个不完整的对象,无法正确上传。
请查看此博客文章,了解更多信息:https://www.rainerhahnekamp.com/en/spring-mvc-json-serialization/
答案 1 :(得分:0)
我通过创建这样的自定义Formatter
来解决它:
public class BsonDocumentFormatter implements Formatter<Document> {
@Override
public Document parse(String s, Locale locale) throws ParseException {
return Document.parse(s);
}
@Override
public String print(Document document, Locale locale) {
return document.toJson();
}
}
然后我在WebMvcConfigureruration
:
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addFormatter(new BsonDocumentFormatter());
}