spring boot 登录注册 demo (三) -- 前后端传递

时间:2022-04-24
本文章向大家介绍spring boot 登录注册 demo (三) -- 前后端传递,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

前端页面通过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方法,可以得到前端传递的东西;