我有一个具有登录功能的Controller类。当我输入用户名和密码并按submit时,它将调用此控制器并将customer存储在会话中。但让我困惑的是@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 c来存储从customService获得的所有信息,并将其存储到会话中。但是会话会存储客户客户。
如果我像这样改变论点。它正常工作
public Customer getCustomer(@RequestParam String username, @RequestParam String password) {
Customer c = customService.getCustomer(username, password);
return c;
}发布于 2021-12-14 14:37:40
由于@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实例解析如下
如您所见,使用第一次调用,参数值将分配给客户客户.
但是在以后的调用中,会话属性与优先级一起使用。
PS:您的代码可能会引起很多混乱。请参阅:https://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation
https://stackoverflow.com/questions/70350126
复制相似问题