gpt4 book ai didi

java - 如何将 spring @ModelAttribute 与构建器模式一起使用

转载 作者:太空宇宙 更新时间:2023-11-04 11:02:14 25 4
gpt4 key购买 nike

我是构建器模式的新手,并试图找到一种在我的 Spring 模型中使用构建器模式的方法。

我以前的模型具有所有 setter 和 getter 方法,我用 Builder 方法替换了它们,现在的代码如下所示:

public class UserInterests {
private final String user;
private final int interestlevel;

private UserInterests(UserInterestBuilder builder) {
this.user = builder.user;
this.interestlevel = builder.interestlevel;
}

public String getUser() {
return user;
}

public static class UserInterestBuilder {
private String user;
private int interestlevel;

public UserInterestBuilder() {
}

public UserInterestBuilder user(final String userId) {
this.user = user;
return this;
}

public UserInterestBuilder interestLevel(final int interestLevel) {
this.interestLevel = interestLevel;
return this;
}

public UserInterests build() {
return new UserInterests(this);
}
}
}

以前,在没有构建器的情况下,我从 UI (jsp) 获取用户兴趣级别并将其绑定(bind)到 UserInterests 模型。在 Controller 中,我使用 @ModelAttribute 来获取 UserInterests 的实例并使用它。

Controller 片段:

@RequestMapping(value = "/addInterest", method = RequestMethod.POST)
public ModelAndView addUserInterest(
@ModelAttribute(USER_INTEREST) UserInterests userInterests,
BindingResult result, HttpSession session, ModelAndView model) {
//do something here
}

JSP 片段

<html>
<head></head>
<body>
<form:form modelAttribute="userInterests" action="addInterest"
method="post">
<!-- Do more -->
</body>
</html>

但是,由于我更改了模型以使用构建器,因此我无法使用 userInterests 模型实例,因为它的构造函数是私有(private)的。我可以使用 request.getParameter() 分别获取用户和兴趣级别值,并使用 build 绑定(bind)到 userInterests 模型。但是有没有一种方法可以直接为构建器使用 @ModelAttribute 而不必单独获取值。

任何帮助将不胜感激。

最佳答案

ModelAttribute注释由 ModelAttributeMethodProcessor 处理,属性通过数据绑定(bind)到 Servlet 请求参数来填充。DataBinder 的内部是以下实际执行绑定(bind)的方法

protected void applyPropertyValues(MutablePropertyValues mpvs) {
try {
// Bind request parameters onto target object.
getPropertyAccessor().setPropertyValues(mpvs, isIgnoreUnknownFields(), isIgnoreInvalidFields());
}
catch (PropertyBatchUpdateException ex) {
// Use bind error processor to create FieldErrors.
for (PropertyAccessException pae : ex.getPropertyAccessExceptions()) {
getBindingErrorProcessor().processPropertyAccessException(pae, getInternalBindingResult());
}
}
}

查看 BeanWrapperImpl这是最常见的属性访问器,它有一个基本功能:自动注册默认 property editors除了 JDK 的标准 PropertyEditors 之外,还来自 spring 包,所以基本上它完全链接到 JavaBeans (基本上属性及其访问器具有特殊的命名约定)这意味着它不支持任何其他样式,例如案例生成器模式。

关于java - 如何将 spring @ModelAttribute 与构建器模式一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46775228/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com