Springboot之Thymeleaf 表单标签(表单提交)|第二章-yellowcong

通过post方式提交表单的时候,需要有一个实体类,去接收表单传递的数据类容,在对象的属性读取中,Thymeleaf 提供了两种方式:1、直接通过${userInfo.username} ,这种实体bean + 属性的方式;2、通过选择表达式*{username}的这种方式。 在表单提交的表单中,表单对象需要在界面跳转进来的时候,传递一个表单对象过来,不然就会报错,不知道这个表单对象是什么鬼。

代码地址

https://gitee.com/yellowcong/springboot-thymeleaf/tree/master/chapter2/springboot-thymeleaf1

目录结构

这里写图片描述

表单提交

1、表单界面控制器

这一段代码中,我传递了一个表单对象到了前台界面中,如果我们不这么做,就会找不到表单对象提交的那个实体类了。

/**
* 创建日期:2018年4月5日<br/>
 * 代码创建:黄聪<br/>
 * 功能描述:首页模版<br/>
 * @return
 */
@RequestMapping("/index")
public String index(ModelMap map){
    //单个数据
    map.put("username", "入门案例");

    UserForm user = new UserForm();
    user.setPassword("test_ps");
    user.setUsername("test");

    map.put("userInfo", user);
    return "admin/index";
}

2、表单界面

下面这段代码演示了,通过${}*{}的方式来读取表单类对象了。

<!DOCTYPE html>
<!-- 需要添加
<html  xmlns:th="http://www.thymeleaf.org">
这样在后面的th标签就不会报错
 -->
<html  xmlns:th="http://www.thymeleaf.org">
<head lang="en">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title th:text="${username}">xx</title>
</head>
<body>
<h1 th:text="${username}">Hello World</h1>
<h1>获取对象信息</h1>
<h2>1、通过直接访问对象的方式</h2>
<p th:text="${userInfo.username}"></p>
<p th:text="${userInfo.password}"></p>


<h2>2、通过th:object访问对象的方式</h2>
<div th:object="${userInfo}">
    <p th:text="*{username}"></p>
    <p th:text="*{password}"></p>
</div>

<h1>表单提交</h1>
<!-- 表单提交用户信息,注意字段的设置,直接是*{} -->
 <form action="#" th:action="@{/add}" th:object="${userInfo}" method="post">  
  <input type="text" th:field="*{username}" />  
  <input type="text" th:field="*{password}" />  
  <input type="submit" />  
</form> 
</body>
</html>

3、表单处理类

这个处理请求中,只是简单的将提交的对象数据获取,然后返回到网页了。

/**
 * 创建日期:2018年4月6日<br/>
 * 代码创建:黄聪<br/>
 * 功能描述:处理add请求<br/>
 * @param user
 * @return
 */
@ResponseBody
@RequestMapping(value="/add",method=RequestMethod.POST)
public String add(@ModelAttribute UserForm user){
    String username = user.getUsername();
    String password = user.getPassword();
    return username+"__"+password;
}

实现效果

这里写图片描述

参考文章

https://blog.csdn.net/huihuilovei/article/details/64466548
https://blog.csdn.net/asd_op/article/details/53232039
https://www.cnblogs.com/jiangbei/p/8462294.html

  • 10
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

狂飙的yellowcong

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值