首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >@ModelAttribute混淆

@ModelAttribute混淆
EN

Stack Overflow用户
提问于 2021-12-14 13:58:14
回答 1查看 47关注 0票数 0

我有一个具有登录功能的Controller类。当我输入用户名和密码并按submit时,它将调用此控制器并将customer存储在会话中。但让我困惑的是@ModelAttribute

代码语言:javascript
复制
@Controller
@SessionAttributes("customer")
public class LoginController {
    
    @Autowired
    CustomerService customService;
    
    @ModelAttribute("customer")
    public Customer getCustomer(@ModelAttribute Customer customer) {
        Customer c = customService.getCustomer(customer.getUsername(), customer.getPassword());
        
        return c;
    }
    
    @RequestMapping(method=RequestMethod.POST,value="/login")
    public String submitLoginForm( Model model) {
        
        return "redirect:/";
    }
    
}```

我将使用@ModelAttribute客户端来存储我输入的用户名和密码,并使用Customer c来存储从customService获得的所有信息,并将其存储到会话中。但是会话会存储客户客户。

如果我像这样改变论点。它正常工作

代码语言:javascript
复制
public Customer getCustomer(@RequestParam String username, @RequestParam String password) {
        Customer c = customService.getCustomer(username, password);
        
        return c;
    }
EN

回答 1

Stack Overflow用户

发布于 2021-12-14 14:37:40

由于@ModelAttribute,您的结果可能会有所不同

代码语言:javascript
复制
@ModelAttribute("customer")
public Customer getCustomer(@ModelAttribute Customer customer) {
    Customer c = customService.getCustomer(customer.getUsername(), customer.getPassword()); 
    return c;
}

它类似于:

代码语言:javascript
复制
@ModelAttribute

    public void initCustomer(@ModelAttribute Customer customer,Model model) {
        Customer c = customService.getCustomer(customer.getUsername(), customer.getPassword()); 
        model.addAttribute("customer",c);
    }

initCustomer(@ModelAttribute客户,.)上面的customer实例解析如下

  • 如果已经通过Model添加,则从该模型中删除。
  • 来自HTTP会话的@SessionAttributes。
  • 从URI路径变量通过转换器(下面的示例)。
  • 从默认构造函数的调用。
  • 通过调用具有与Servlet请求参数匹配的参数的“主构造函数”;参数名称通过JavaBeans @ConstructorProperties或字节码中保留的运行时参数名称确定。

如您所见,使用第一次调用,参数值将分配给客户客户.

但是在以后的调用中,会话属性与优先级一起使用。

PS:您的代码可能会引起很多混乱。请参阅:https://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70350126

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档