繁体   English   中英

@SessionAttribute 令人困惑

[英]@SessionAttribute confusing

我有一个具有登录功能的 Spring Controller class。 它有两种方法:getCustomer 从数据库中获取客户信息保存在 session 中,submitLoginForm 检查客户(或用户)是否登录成功(如果 getCustomer 返回 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 ,因为我们的 form("view".) 不需要/使用它。 (尽可能多地看到)
  • 但反而:
    • 发送@RequestParamsubmitLoginForm() (根据 html 表单)
    • 在成功登录时添加模型/会话属性(即在表单提交时)。

在此之后( model.addAttribute ),我们可以从 session 中的任何视图/控制器访问"customer" (模型/会话)属性(由于/感谢 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() ..)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM