【问题标题】:@ModelAttribute confusing@ModelAttribute 令人困惑
【发布时间】:2022-01-17 20:07:30
【问题描述】:

我有一个具有登录功能的控制器类。当我输入用户名和密码并按提交时,它将调用此控制器并将客户信息存储在会话中。但让我感到困惑的一件事是@ModelAttribute

@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 客户来存储我输入的用户名和密码,并使用 Customer c 来存储我从 customService 获得的所有信息并将其存储到会话中。但会话存储的是 Customer 客户。

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

public Customer getCustomer(@RequestParam String username, @RequestParam String password) {
        Customer c = customService.getCustomer(username, password);
        
        return c;
    }

【问题讨论】:

  • @FahimazazBhanej 我正在开发一个 Spring Boot 项目。上面的控制器将负责登录功能。我将在登录页面输入用户名和密码。如果登录成功,索引页面将显示客户的全名

标签: java spring-mvc


【解决方案1】:

您的结果可能会因@ModelAttribute 而有所不同

@ModelAttribute("customer")
public Customer getCustomer(@ModelAttribute Customer customer) {
    Customer c = customService.getCustomer(customer.getUsername(), customer.getPassword()); 
    return c;
}

类似于:

@ModelAttribute

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

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

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

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

但后来调用,会话属性优先使用。

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

【讨论】:

    猜你喜欢
    • 2022-01-21
    • 2018-02-26
    • 2012-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-06
    相关资源
    最近更新 更多