前端頁面通過thymeleaf渲染
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
前后端的傳遞關鍵在html上面,請看代碼:
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8" /> <title>Insert title here</title> <link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.4/css/bootstrap.min.css" /> </head> <body> <div class="container"> <div class="row clearfix"> <div class="col-md-3 column"> <form role="form" method="POST" th:action="@{/userLogin}" th:object="${user}"> <label for="username">Name</label><input type="text" class="form-control" id="username" th:field="*{name}" /> <label for="password">Password</label><input type="password" class="form-control" id="password" th:field="*{password}" /> <button type="submit" class="btn btn-default">Sign in</button> </form> <ul class="nav nav-pills"> <li role="presentation"><a href="register.html" class="href" target="_blank">Sign up</a></li> </ul> </div> </div> </div> </body> </html>
th:action="@{/userLogin}" 表示這個form表單的action會指向/userLogin
th:object="${user}" 表示form表單的內容會以user的形式傳遞
th:field:"*{name}" 表示該input輸入的值,也就是前端的值存儲在name中
如果你在前端輸入name=jwen,password=1234,當這個表單提交的時候,就會把name=jwen,password=1234存放在user中傳遞給/userLogin
那么看看controller層怎么接接收這個的
@RequestMapping(value = "/userLogin", method = RequestMethod.POST) String userLogin(User user, Model model) { boolean verify = userService.verifyUser(user); if (verify) { model.addAttribute("name", user.getName()); model.addAttribute("password", user.getPassword()); return "result"; } else { return "redirect:/notVerify"; } }
requestMapping將/userLogin綁定給userLogin方法,該方法的入參是一個User的實例,一個Model的實例
而這個User的實例,就是我們從前端傳遞的,就是說你在userLogin方法,可以得到前端傳遞的東西;