后台向前台【视图】传递数据

后台通过Map向前台传递实体参数

实体:@Entity@Table(name = "tbl_user")

public class User1 implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="user_no")
    private int userNo;

    @NotEmpty(message="姓名不能为空")
    @Column(name="user_name")
    private String userName;
    @NotEmpty(message="密码不能为空")
    //@Length(min=6,message="密码长度不能小于6位")
    //@Length(max=8,message="密码长度不能大于8位")
    private String userPwd;
    public User1(String name,String pwd){
        this.userName=name;
        this.userPwd=pwd;
    }
    public User1(){};
.......
}

 

控制层代码

@Controller
@RequestMapping("/security")
public class SecurityController {

    @Autowired
    private User1Service userService ;

    @GetMapping("/toLogin")
    public String toLogin(Map<String, Object> map) {        必须作为方法的参数,否则无法传递到前端
        map.put("user", new User1("user1","pwd1"));
        return "login";
    }

前端 login.html :

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>课程管理系统登录页面</title>
  <link rel="stylesheet" type="text/css" th:href="@{/css/style.css}" />
  <script type="text/javascript" th:src="@{/js/jquery-3.1.1.min.js}"></script>
</head>
<body>
<div>
  <div id="wrapper" style="text-align:center">
    <img id="login"   width="100" height="20"   th:src="@{/pics/logo.png}" />
    <div id="f_title">课程管理系统用户登录</div>
    <!--${user}取后台转递的map参数,其中有个key是user-->
    <form th:action="@{/security/login}" method="post" th:object="${user}">  // 取参数map的key=user的实体对象 
      <div  class="f_row">
        <span>用户姓名:</span>
        <input type="text" class="form-control" name="userName" th:value="*{userName}" placeholder="请输入姓名">  Thymeleaf取实体对象成员 userName的值 ,如果=null , 则显示:请输入姓名
      </div>
      <div class="f_row">
        <span>登录密码:</span>
        <input type="text" class="form-control" name="userPwd" th:value="*{userPwd}" placeholder="请输入密码">    必须要用 th:value取值,否则即使name的名称和实体成员名称一致也不会显示值
      </div>
      <br>
      <div class="f_row">
        <input type="submit" value=" 登 录 "></input>
        <a th:href="@{/security/register}"  target="_blank">注册</a>
      </div>
    </form>
  </div>
</div>
<div id="footer">
  <div th:insert="footer :: copy"></div>
  <div th:insert="footer :: time"></div>
</div>
</body>
</html>

 

运行结果

 

 

posted @ 2021-07-22 16:15  清语堂  阅读(68)  评论(0编辑  收藏  举报