【发布时间】:2022-01-21 01:07:05
【问题描述】:
我有一个具有登录功能的 Spring Controller 类。它有两种方法:getCustomer 从数据库中获取客户信息以保持会话, 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";
}
}
}
当我使用真实的用户名和密码登录时,我得到的是错误页面而不是主页。但是当我输入主页网址时,主页会显示我已成功登录的用户名
这是我的登录表单
<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>
【问题讨论】:
-
显示您的表格! (听起来总是
customer==null(在后期映射中)?) -
..当页面第一次加载时,
@RequestParam String username, @RequestParam String password是什么? (没有查询/参数!?););) -
@xerx593 我已经在我的问题上添加了我的登录表单
-
@xerx593 不,参数中的客户似乎最初具有空值(这导致错误页面和登录失败)。但是当我通过输入url跑到主页时,客户不再为空(登录突然成功)
标签: java spring-mvc