今天我们说一下springboot项目中,前端如何使用thymeleaf提交form表单数据到后台controller中,这与jsp还是有些区别的。
第一步,修改thymeleaf的页面:

<form method="post" th:action="@{/login}" th:object="${user}" class="loginForm">
                <div class="loginInputDiv">
                    <label for="name" class="loginLabel"><img
                            th:src="@{/images/fore/WebsiteImage/2018-04-27_235518.png}"
                            width="38px" height="39px" title="会员名"/></label>
                    <input type="text" th:field="*{userName}" id="name" class="loginInput" placeholder="会员名/邮箱/手机号">
                </div>
                <div class="loginInputDiv">
                    <label for="password" class="loginLabel"><img
                            th:src="@{/images/fore/WebsiteImage/2018-04-27_235533.png}"
                            width="38px" height="39px" title="登录密码"/></label>
                    <input type="password" th:field="*{userPassword}" id="password" class="loginInput">
                </div>
                <input type="submit" class="loginButton" value="登 录">
            </form>

        注意:
        1,th:action 是要跳转的url。
        2,th:object 是后台跳转到登录页面之前时,封装好的POJO实例对象

        点击按钮提交表单之后,根据路径找到相应的controller方法,具体方法如下:

        Controller

	//跳转到登录页面
	//客户get请求一个form页面时,返回的model里有一个空User实例,去绑定页面的th:object,如果没有绑定的话会报错
    @RequestMapping("/toLogin")
    public String toLogin(Model model){
        model.addAttribute("user",new User());
        return "fore/loginPage";//返回到登录页面
    }
    //执行登录操作
    //form表单的提交映射到此处,@ModelAttribute映射页面的th:object,从而将form捕获并封装成User对象
    @RequestMapping("/login")
    public String Login(@ModelAttribute User user){
        System.out.println("===========登录===========");
        System.out.println("==========name:"+user.getUserName());
        System.out.println("===========pwd:"+user.getUserPassword());
        return "fore/homePage";//返回登录成功之后的主页面
    }

        POJO:

public class User {

  private long userId;
  private String userName;
  private String userPassword;
  public String getUserName() {
    return userName;
  }
  public void setUserName(String userName) {
    this.userName = userName;
  }
  public String getUserPassword() {
    return userPassword;
  }
  public void setUserPassword(String userPassword) {
    this.userPassword = userPassword;
  }
}

        运行一下结果,在页面中输入name:mengmeng,密码:123,控制台打印结果:

在这里插入图片描述

        这就说明后台成功接收前端的数据。大家要是觉得不错的话,可以给梦梦点点关注。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐