我有一個具有登錄功能的 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";
}
}
}
當我使用真實的用戶名和密碼登錄時,我看到的是錯誤頁面而不是主頁。但是當我輸入主頁 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>
uj5u.com熱心網友回復:
這樣做(未經測驗):
@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";
}
}
}
- 不要“暴露” any
@ModelAttribute,因為我們的 form("view"!) 不需要/使用它。(盡可能多地看到) - 但反而:
- 發送
@RequestParams 到submitLoginForm()(根據 html 形式) - 在成功登錄時添加模型/會話屬性(即在表單提交時)。
- 發送
在此 ( model.addAttribute) 之后,我們可以"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()..)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/385842.html
上一篇:將類的實體添加到串列中
