Spring Boot中Thymeleaf对表单处理的一些用法:
(1)使用th:field属性:进行表单字段绑定
(2)使用ids对象:一般用于lable配合radio或checkbox使用
(3)表单提交处理

开发环境:IntelliJ IDEA 2019.2.2
Spring Boot版本:2.1.8

新建一个名称为demo的Spring Boot项目。
pom.xml 依赖项如下:

       <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>

一、使用th:field属性

th:field属性常用于表单字段绑定,除了自动生成id和name属性,对不同的节点类型还会有不同的生成逻辑。
例如input还会再生成value属性,textarea会自动设文本,select会自动选中相应的选项,如果是同个表单属性,radio和checkbox的id会全局自动增长。
备注:
(1)使用th:field属性时,如果html节点中已经存在相应属性,则不会再另外生成。
(2)th:field属性需要使用星号表达式*{...},即先使用th:object声明表单对象,再使用th:field=*{...}对表单域进行处理。

1、src/main/java/com/example/demo/User.java

package com.example.demo;

public class User {
String name;
Integer sex;
String[] MyColors; public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public String[] getMyColors() {
return MyColors;
}
public void setMyColors(String[] myColors) {
MyColors = myColors;
}
}

2、src/main/java/com/example/demo/FieldController.java

package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping; import java.util.HashMap;
import java.util.Map; @Controller
public class FieldController {
@RequestMapping("/field")
public String field(Model model){
//设置用户对象
User user = new User();
user.setName("小红");
user.setSex(0);
model.addAttribute("user", user);
//设置性别
Map<String, Object> sexes = new HashMap<String, Object>();
sexes.put("男", 1);
sexes.put("女", 0);
model.addAttribute("sexes", sexes);
return "field";
}
}

3、src/main/resources/templates/field.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>使用th:field属性</title>
</head>
<body>
<form th:object="${user}">
<input type="text" th:field="*{name}" id="name1" />
<input type="text" th:field="*{name}" />
<input type="text" th:field="*{name}" />
<textarea th:field="*{name}"></textarea>
<textarea th:field="*{name}"></textarea>
<select th:field="*{sex}">
<option th:each="sex : ${sexes}" th:value="${sex.value}" th:text="${sex.key}"></option>
</select>
<select th:field="*{sex}">
<option th:each="sex : ${sexes}" th:value="${sex.value}" th:text="${sex.key}"></option>
</select>
<input type="checkbox" th:field="*{name}" value="*{name}"/>
<input type="checkbox" th:field="*{name}" value="*{name}"/>
<input type="radio" th:field="*{name}" value="*{name}"/>
<input type="radio" th:field="*{name}" value="*{name}"/>
</form>
</body>
</html>

启动服务后,浏览器访问http://localhost:8080/field,网页源代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>使用th:field属性</title>
</head>
<body>
<form>
<input type="text" id="name1" name="name" value="小红" />
<input type="text" id="name" name="name" value="小红" />
<input type="text" id="name" name="name" value="小红" />
<textarea id="name" name="name">小红</textarea>
<textarea id="name" name="name">小红</textarea>
<select id="sex" name="sex">
<option value="0" selected="selected">女</option>
<option value="1">男</option>
</select>
<select id="sex" name="sex">
<option value="0" selected="selected">女</option>
<option value="1">男</option>
</select>
<input type="checkbox" value="*{name}" id="name1" name="name"/><input type="hidden" name="_name" value="on"/>
<input type="checkbox" value="*{name}" id="name2" name="name"/><input type="hidden" name="_name" value="on"/>
<input type="radio" value="*{name}" id="name3" name="name"/>
<input type="radio" value="*{name}" id="name4" name="name"/>
</form>
</body>
</html>

二、使用ids对象

可以使用ids对象的seq方法生成指定名称的递增id。
对于radio和checkbox自动生成的id,配合lable节点使用时,需要知道这个id,可以使用ids对象的prev和next方法。

1、src/main/java/com/example/demo/IdsController.java

package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping; @Controller
public class IdsController {
@RequestMapping("/ids")
public String ids(Model model){
User user = new User();
user.setName("小红");
user.setSex(0);
model.addAttribute("user", user);
return "ids";
}
}

2、src/main/resources/templates/ids.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>使用ids对象</title>
</head>
<body>
<form th:object="${user}">
<input type="text" th:field="*{name}" th:id="${#ids.seq('tname')}" />
<input type="text" th:field="*{name}" th:id="${#ids.seq('tname')}" /> <input type="radio" th:field="*{name}" value="*{name}" th:id="${#ids.seq('rname')}"/>
<input type="radio" th:field="*{name}" value="*{name}" th:id="${#ids.seq('rname')}"/> <input type="checkbox" th:field="*{name}" value="*{name}" th:id="${#ids.seq('cname')}" />
<input type="checkbox" th:field="*{name}" value="*{name}" th:id="${#ids.seq('cname')}"/> <input type="radio" th:field="*{name}" value="*{name}" />
<label th:for="${#ids.prev('name')}" th:text="单选A"></label>
<input type="radio" th:field="*{name}" value="*{name}" />
<label th:for="${#ids.prev('name')}" th:text="单选B"></label> <label th:for="${#ids.next('name')}" th:text="多选A"></label>
<input type="checkbox" th:field="*{name}" value="*{name}" />
<label th:for="${#ids.next('name')}" th:text="多选B"></label>
<input type="checkbox" th:field="*{name}" value="*{name}" />
</form>
</body>
</html>

启动服务后,浏览器访问http://localhost:8080/ids,网页源代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>使用ids对象</title>
</head>
<body>
<form>
<input type="text" id="tname1" name="name" value="小红" />
<input type="text" id="tname2" name="name" value="小红" /> <input type="radio" value="*{name}" id="rname1" name="name"/>
<input type="radio" value="*{name}" id="rname2" name="name"/> <input type="checkbox" value="*{name}" id="cname1" name="name" /><input type="hidden" name="_name" value="on"/>
<input type="checkbox" value="*{name}" id="cname2" name="name"/><input type="hidden" name="_name" value="on"/> <input type="radio" value="*{name}" id="name1" name="name" />
<label for="name1">单选A</label>
<input type="radio" value="*{name}" id="name2" name="name" />
<label for="name2">单选B</label> <label for="name3">多选A</label>
<input type="checkbox" value="*{name}" id="name3" name="name" /><input type="hidden" name="_name" value="on"/>
<label for="name4">多选B</label>
<input type="checkbox" value="*{name}" id="name4" name="name" /><input type="hidden" name="_name" value="on"/>
</form>
</body>
</html>

三、表单的提交处理

提交后,在控制器方法中使用@ModelAttribute映射表单对象。

1、src/main/java/com/example/demo/FormController.java

package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping; import java.util.Arrays;
import java.util.HashMap;
import java.util.Map; @Controller
public class FormController {
@RequestMapping("/form")
public String form(Model model){
setConstant(model);
User user = new User();
user.setName("小明");
user.setSex(1);
user.setMyColors(new String[]{"white", "black"});
model.addAttribute("user", user);
return "form";
} @PostMapping("/submit")
public String submit(@ModelAttribute User user, Model model){
setConstant(model);
model.addAttribute("user", user);
System.out.println("姓名:" + user.getName());
System.out.println("性别:" + (user.getSex().intValue() == 1 ? "男" : "女"));
System.out.println("喜欢的颜色:" + Arrays.toString(user.getMyColors()));
//return "redirect:/form";
return "form";
} //设置常量
private void setConstant(Model model){
Map<String, Object> sexes = new HashMap<String, Object>();
sexes.put("男", 1);
sexes.put("女", 0);
model.addAttribute("sexes", sexes);
String[] colors = new String[]{"red", "white", "black"};
model.addAttribute("colors", colors);
}
}

2、src/main/resources/templates/form.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>表单的提交处理</title>
</head>
<body>
<form method="post" th:action="@{/submit}" th:object="${user}">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" th:field="*{name}" /></td>
</tr>
<tr>
<td>性别:</td>
<td><select th:field="*{sex}">
<option th:each="sex : ${sexes}" th:value="${sex.value}" th:text="${sex.key}"></option>
</select>
</td>
</tr>
<tr>
<td>喜欢的颜色:</td>
<td>
<span th:each="color : ${colors}">
<input type="checkbox" th:field="*{myColors}" th:value="${color}" />
<label th:for="${#ids.prev('myColors')}" th:text="${color}"></label>
</span>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="提交" />
</td>
</tr> </table> </form>
</body>
</html>

启动服务后,浏览器访问http://localhost:8080/from,页面如下图:

网页源代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>表单的提交处理</title>
</head>
<body>
<form method="post" action="/submit">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" id="name" name="name" value="小明" /></td>
</tr>
<tr>
<td>性别:</td>
<td><select id="sex" name="sex">
<option value="0">女</option>
<option value="1" selected="selected">男</option>
</select>
</td>
</tr>
<tr>
<td>喜欢的颜色:</td>
<td>
<span>
<input type="checkbox" value="red" id="myColors1" name="myColors" /><input type="hidden" name="_myColors" value="on"/>
<label for="myColors1">red</label>
</span><span>
<input type="checkbox" value="white" id="myColors2" name="myColors" checked="checked" /><input type="hidden" name="_myColors" value="on"/>
<label for="myColors2">white</label>
</span><span>
<input type="checkbox" value="black" id="myColors3" name="myColors" checked="checked" /><input type="hidden" name="_myColors" value="on"/>
<label for="myColors3">black</label>
</span>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="提交" />
</td>
</tr> </table> </form>
</body>
</html>

点击提交按钮,IDEA控制台输出:

姓名:小明
性别:男
喜欢的颜色:[white, black]

Spring Boot 2 + Thymeleaf:表单字段绑定、表单提交处理的更多相关文章

  1. 一个小demo熟悉Spring Boot 和 thymeleaf 的基本使用

    目录 介绍 零.项目素材 一. 创建 Spring Boot 项目 二.定制首页 1.修改 pom.xml 2.引入相应的本地 css.js 文件 3.编辑 login.html 4.处理对 logi ...

  2. Spring Boot(十五):spring boot+jpa+thymeleaf增删改查示例

    Spring Boot(十五):spring boot+jpa+thymeleaf增删改查示例 一.快速上手 1,配置文件 (1)pom包配置 pom包里面添加jpa和thymeleaf的相关包引用 ...

  3. Spring Boot2 系列教程(九)Spring Boot 整合 Thymeleaf

    虽然现在慢慢在流行前后端分离开发,但是据松哥所了解到的,还是有一些公司在做前后端不分的开发,而在前后端不分的开发中,我们就会需要后端页面模板(实际上,即使前后端分离,也会在一些场景下需要使用页面模板, ...

  4. 极简 Spring Boot 整合 Thymeleaf 页面模板

    虽然现在慢慢在流行前后端分离开发,但是据松哥所了解到的,还是有一些公司在做前后端不分的开发,而在前后端不分的开发中,我们就会需要后端页面模板(实际上,即使前后端分离,也会在一些场景下需要使用页面模板, ...

  5. Spring Boot和Thymeleaf整合,结合JPA实现分页效果

    在项目里,我需要做一个Spring Boot结合Thymeleaf前端模版,结合JPA实现分页的演示效果.做的时候发现有些问题,也查了现有网上的不少文档,发现能全栈实现的不多,所以这里我就把我的做法, ...

  6. 如何设置织梦cms自定义表单字段为必填项

    1.编辑器打开\plus\diy.php2.在40行左右找到此行代码:$dede_fields = empty($dede_fields) ? '' : trim($dede_fields);3.在这 ...

  7. Spring Boot整合 Thymeleaf 模板引擎

    什么是Thymeleaf Thymeleaf是一款用于渲染XML.XHTML.HTML5内容的模板引擎.类似Velocity,FreeMaker模板引擎,它也可以轻易的与Spring MVC等Web框 ...

  8. spring boot 与 thymeleaf (2): 常用表达式

    在asp.net mvc 中, 有一个视图解析器, 可以支持Razor语法. 使用起来, 是非常的方便, 并且, 写在前台页面的后台方法, 是可调试的. 但是在java中, 目前我还没有接触到, 像. ...

  9. 嵌入式表单字段中的内容可能被server更改以删除不安全的内容。是否要又一次载入您的页面以查看保存结果?

    嵌入式表单字段中的内容可能被server更改以删除不安全的内容.是否要又一次载入您的页面以查看保存结果?         近期有朋友问到,当他在SharePoint首页上进行编辑时.插入一段代码. 完 ...

随机推荐

  1. iOS WKWebView与JS的交互

    参考链接:https://www.jianshu.com/p/524bc8699ac2

  2. WinCC的电子签名与审计追踪

    如何写入审计追踪记录 用脚本向Audit中添加记录有两种方法,一种方法是用InserAuditEntryNew函数写入,另一种方法是生成属于“操作员输入消息”类型的报警消息,该报警消息会记录到Audi ...

  3. java之不同数据流应用举例

    按操作单位的不同分为:字节流(8bit)(InputStream.OuputStream).字符流(16bit)(Reader.Writer) 按数据流的流向不同分为:输入流.输出流 按角色的不同分为 ...

  4. 第二个视频作品《[SpringCloudAlibaba]微服务之注册中心nacos》上线了

    1.场景描述 第二个视频作品出炉了,<[SpringCloudAlibaba]微服务之注册中心nacos>上线了,有需要的朋友可以直接点击链接观看.(如需购买,请通过本文链接购买) 2. ...

  5. C#中转换运算符explicit、implicit、operator、volatile研究

    C#中的这个几个关键字:explicit.implicit与operator,估计好多人的用不上,什么情况,这是什么?字面解释:explicit:清楚明白的;易于理解的;(说话)清晰的,明确的;直言的 ...

  6. How to: Use the Entity Framework Model First in XAF 如何:在 XAF 中使用EF ModelFirst

    This topic demonstrates how to use the Model First entity model and a DbContext entity container in ...

  7. EXCEPTION_ACCESS_VIOLATION(0xc0000005)

    EXCEPTION_ACCESS_VIOLATION(0xc0000005)eclipse.ini中添加:-XX:CompileCommand=exclude,org.eclipse.jdt.inte ...

  8. MySQL日志简介

    一.MySQL日志简介 二.错误日志 作用: 记录mysql数据库的一般状态信息及报错信息,是我们对于数据库常规报错处理的常用日志. 默认位置: $MYSQL_HOME/data/ 开启方式:(MyS ...

  9. docker容器虚拟化技术

    简单来说,在Windows系统下安装各种运行环境的坑简直不要太多了(● ̄(エ) ̄●),并不仅限于docker.Nginx.PHP.Python等等,我会尽详细写出实际过程中遇到的各种各样的奇葩问题 1 ...

  10. unittest框架之 BeautifulReport 模板报告生成的正确姿势

    使用unittest框架的自动化测试,报告一定很重要,目前介绍一个比较高大上的报告模板 BeautifulReport.如果首次使用的话需要安装 pip install beautifulreport ...