自学 使用thymeleaf提交form表单给controller(springboot)

本文介绍了Spring Boot项目里,前端使用Thymeleaf提交form表单数据到后台Controller的方法。说明了修改Thymeleaf页面时,th:action和th:object的作用,点击按钮提交表单后会根据路径找到对应Controller方法,最后通过示例验证后台成功接收前端数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        今天我们说一下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,控制台打印结果:

在这里插入图片描述

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

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梦梦~~

你的鼓励是对我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值