【问题标题】:How to use beans in model attribute in Spring framework如何在 Spring 框架的模型属性中使用 bean
【发布时间】:2013-05-21 17:49:22
【问题描述】:

你好可能是个愚蠢的问题,但我是 Spring 框架的新手。请帮忙

web.xml

<display-name>demo name</display-name>
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener </listener-class>
</listener>

applicationcontext.xml

<bean id="loginInfo" class="com.saurabh.dto.LoginInfo"></bean>
<bean id="contactInfo" class="com.saurabh.dto.ContactInformation"></bean>

<bean id="userDTO" class="com.saurabh.dto.UserDTO" scope="request"  abstract="false">
    <property name="login" ref="loginInfo"></property>
    <property name="contact" ref="contactInfo"></property>
</bean>

控制器

 @Controller
 public class LogonController {

@RequestMapping(value = "/requestLogon.htm",method={RequestMethod.POST,RequestMethod.GET})
public String registerUser(@ModelAttribute("userDTO") UserDTO user, BindingResult result, HttpServletRequest request, HttpServletResponse response,
        HttpSession session)throws Exception{

现在的问题是,在控制器 UserDTO 用户中,我将登录属性设置为 null,但根据接线,我已经注入了它。请解释问题..

【问题讨论】:

  • 但是您在registerUser 方法中的userDTO 不是您在applicationContext.xml 中创建的方法,而是您用作相应表单的模型属性的方法。
  • @Rahaman 谢谢。这可能是问题,但解决方案是什么。?我完全不知道。

标签: java spring jakarta-ee spring-mvc inversion-of-control


【解决方案1】:

您最好在注解 @ModelAttribute 的方法中创建 UserDTO,而不是在 Spring applicationContext.xml 中指定它

@ModelAttribute("userDTO")
public UserDTO createModel() {
    UserDTO userDto = new UserDTO();
    userDto.setLogin(new LoginInfo());
    userDto.setContact(new ContactInformation());
    return userDto;
}

这将为每个请求创建并返回一个新的 UserDTO 对象 - Spring 会将表单数据绑定到该对象。

【讨论】:

  • OK 这只是一个解决方案,但我需要确切的解决方案。虽然这次也填充了属性,但它没有使用布线,我希望它们被使用。
【解决方案2】:

@ModelAttribute 在方法参数上表示应该从模型中检索参数。如果模型中不存在,则应首先实例化参数,然后将其添加到模型中。

因此,在您的情况下,由于 UserDTO 尚未在模型中,因此 Spring 创建了一个新对象“userDTO”,该对象显然具有带有 null 值的登录变量。这类似于UserDTO userDTO = new UserDTO(); userDTO.login 在这种情况下为空。

Will Keeling 的回答是正确的。当使用 createdModel 方法创建 userDTO 模型时(正如他所提到的),Spring 将进行数据绑定,并且用户对象字段将从 所有具有匹配名称的请求参数中填充。即如果您尝试使用 URL /requestLogon.htm?login.username=ABC(假设您在 LoginInfo 中有用户名字段),则用户名将被正确绑定。

【讨论】:

  • 好的,我同意你的回答,这对我理解基础概念有很大帮助,但是如果我不想这样做,我希望我的数据填充到连接的 bean 中在 applicationcontext.xml 中,这样我还将获得 DI 注入的数据以及表单数据。
  • Saurabh,您希望何时填充数据?在 JSP 表单的帖子上?如果是这样,您需要在 jsp 中的表单元素上使用 modelAttribute。您最好将 GET 和 POST 请求的控制器处理程序方法分开。然后你会更好地理解和调试它。
猜你喜欢
  • 2012-08-28
  • 1970-01-01
  • 2021-12-08
  • 2011-04-26
  • 1970-01-01
  • 2020-06-02
  • 1970-01-01
  • 2017-10-05
  • 2017-09-02
相关资源
最近更新 更多