1.前端傳資料后端接收:
用戶在登錄界面輸入用戶名和密碼傳給后端controller,由后端判斷是否正確!
在html界面中要傳遞的資料name命名,通過表單的提交按鈕會傳遞給回應的controller,在controller將需要的name接收!
<input type="text" name="username" class="form-control" th:placeholder="#{login.username}">
<input type="password" name="password" class="form-control" th:placeholder="#{login.password}">
在controller中使用@RequestParam來對應接收前端要傳遞的引數,此時引數名嚴格對應html界面中提交的資料name名稱!
@RequestMapping("/user/login")
public String Login(@RequestParam("username") String username,
@RequestParam("password") String password,
Model md){
}
此時后端就實作接收前端傳遞的資料
2.后端對資料判斷后回傳資訊給前端:
controller通過上述引數會接受到html,傳遞的資料,對資料進行判斷,并且通過msg將資訊傳遞回去,
if(!StringUtils.isEmpty(username)&& "123123".equals(password)){
return "redirect:/main.html";
}else{
md.addAttribute("msg","用戶名或者密碼錯誤!");
return "index";
}
html頁面使用thymeleaf引擎接收并且顯示資料在界面!
<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
完整的兩個代碼塊如下:
<form class="form-signin" th:action="@{user/login}">
<img class="mb-4" th:src="@{/img/bootstrap-solid.svg}" alt="" width="72" height="72">
<h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>
<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
<input type="text" name="username" class="form-control" th:placeholder="#{login.username}" required="" autofocus="" >
<input type="password" name="password" class="form-control" th:placeholder="#{login.password}" required="" >
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me" th:text="#{login.remember}">
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.btn}">sign in</button>
<p class="mt-5 mb-3 text-muted">? 2022-7-8//21:41</p>
<a class="btn btn-sm" th:href="@{/index.html(l='zh_CN