thymeleaf實現前後端數據交換

 

 

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')}">中文</a>
			<a class="btn btn-sm" th:href="@{/index.html(l='en_US')}">English</a>
		</form>

java

@Controller
public class LoginController {
    @RequestMapping("/user/login")
    public String Login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        Model md){
        if(!StringUtils.isEmpty(username)&& "123123".equals(password)){
            return "redirect:/main.html";
        }else{
            md.addAttribute("msg","用戶名或者密碼錯誤!");
            return "index";
        }

    }
}

在這裡插入圖片描述

Tags: