@SessionAttribute 令人困惑

@SessionAttribute confusing

我有一个 Spring 控制器 class,它具有登录功能。它有两种方法:getCustomer 从数据库中获取客户信息以保持在会话中,submitLoginForm 检查客户(或用户)是否登录成功(如果 getCustomer return null 和 运行 错误页面则登录失败)。但是让我感到困惑的一件事是当我输入真实的用户名和密码时

@Controller
@SessionAttributes("customer")
public class LoginController {
    
    @Autowired
    CustomerService customService;
    
    // get username and password to log in
    @ModelAttribute("customer")
    public Customer getCustomer(@RequestParam String username, @RequestParam String password) {

            Customer c = customService.getCustomer(username, password);
            return c;
    }
    
    @RequestMapping(method=RequestMethod.POST,value="/login")
    public String submitLoginForm(@SessionAttribute(required=false) Customer customer, Model model) {
        
        if(customer != null) {
            // login successfully
            return "redirect:/";
        } else {
            // login unsuccessfully
            model.addAttribute("message","wrong username or password");
            return "error";
        }
    }
}

当我使用真实的用户名和密码登录时,我看到的是错误页面而不是主页。但是当我输入主页时 url 主页显示了我登录成功的用户名

这是我的登录表单

<form action="login" method="POST">
    <input type="text" placeholder="Name" name="username" required/>
    <input type="text" placeholder="Password" name="password" required/>
                            
    <button type="submit" class="btn btn-default">Login</button>
</form>

这样做(未经测试):

@Controller
@SessionAttributes("customer")
public class LoginController {

    @Autowired
    CustomerService customService;

    @RequestMapping(method=RequestMethod.POST,value="/login")
    public String submitLoginForm(
      @RequestParam String username, 
      @RequestParam String password,
      Model model
    ) {
        Customer customer = customService.getCustomer(username, password);
        if(customer != null) {
            // login successfully
            model.addAtribute("customer", customer); // !!
            return "redirect:/";
        } else {
            // login unsuccessfully
            model.addAttribute("message","wrong username or password");
            return "error";
        }
    }
}
  • 不要“暴露”任何 @ModelAttribute,因为我们的表单(“查看”!)不会 need/use 它。 (见多识广)
  • 而是:
    • 发送@RequestParams给submitLoginForm()(根据html表格)
    • 在成功登录时添加 model/session 属性(即在提交表单时)。

在此 (model.addAttribute) 之后,我们可以从该会话中的任何 view/controller 访问 "customer" (model/session) 属性(due/thx 到 SessionAttributes 注释).


要实现这一点:

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

我们已经必须像这样调用 (GET) 它:/login?username=admin&password=se3cret(超过 submitLoginForm()..)。