Thymeleaf (select、checkbox)数据绑定和数据回回显

本文详细介绍了Thymeleaf在Web应用中如何进行数据绑定和回显,包括select下拉框和checkbox的选择项填充及状态保持,适用于前端与后端开发人员学习。

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

第一种情况:select 数据绑定:

前端页面:

<div class="col-sm-10">
					<select name="type"  id="type" class="form-control">
						<option value=''>请数据类型</option>
    					<option th:each="map : ${dataType}" th:text="${map.key}" th:value="${map.value}">
    					</option>
					</select>
				</div>

后台代码:

	// 跳转至新增页面
	@RequestMapping(value = "/insertPage", method = { RequestMethod.GET })
	public String insertPage(Model model) {
		Map<String, Object> map = MySQLConstant.getMySQLDataType();
		model.addAttribute("dataType", map);
		return "field/add";
	}

 

第二情况:select 数据回显:

前端页面:

<div class="form-group">
				<label for="type" class="col-sm-2 control-label">数据类型</label>
				<div class="col-sm-10">
					<select name="type"  id="type" class="form-control" th:field="*{type}">
						<option th:each="map:${dataType}" th:text="${map.key}" th:value="${map.value}" th:selected="${type eq map.value}">
    					</option>
					</select>
				</div>
			</div>

后台代码:

// 跳转至更新页面
	@RequestMapping(value = "/updatePage")
	public String update(Model model, String sid) {
		Column entity = service.selectByPrimaryKey(sid);
		model.addAttribute("entity", entity);
		Map<String, Object> map = MySQLConstant.getMySQLDataType();
		model.addAttribute("dataType", map);

		Map<String, Object> requiredMap = new HashMap<String, Object>();
		requiredMap.put("否", "2");
		requiredMap.put("是", "1");
		model.addAttribute("requiredMap", requiredMap);

		Map<String, Object> primaryMap = new HashMap<String, Object>();
		primaryMap.put("否", "2");
		primaryMap.put("是", "1");
		model.addAttribute("primaryMap", primaryMap);
		return "field/update";
	}

第三种情况:checkbox 数据绑定

前端页面:

<div class="form-group">
				<label for="required" class="col-sm-2 control-label">是否必填</label>
				<div class="col-sm-10">
					<!--  
					<input type="text" class="form-control" name="required"
						id="required" placeholder="在此输入控件名称" />-->
					<div class="form-control">
	   					<label class="checkbox-inline">
	      					<input type="checkbox" id="required" name="required" value="1"> 是
	   					</label>
	   					<label class="checkbox-inline">
	      					<input type="checkbox" id="required" name="required" value="2"> 否
	  					</label>
					</div>
				</div>
			</div>

第四种情况:checkbox 数据回显

前端页面:

<div class="form-group">
				<label for="required" class="col-sm-2 control-label">是否必填</label>
				<div class="col-sm-10">
					<div class="form-control">
					<input type ="checkbox" name="required" th:field="*{required}"
						th:each ="map : ${requiredMap}"
						th:value="${map.value}"
						th:text ="${map.key}"
						th:attr ="checked=${map.value eq required ? true : false}">
					</div>
				</div>
			</div>

后台代码:

@RequestMapping(value = "/updatePage")
	public String update(Model model, String sid) {
		Column entity = service.selectByPrimaryKey(sid);
		model.addAttribute("entity", entity);
		Map<String, Object> map = MySQLConstant.getMySQLDataType();
		model.addAttribute("dataType", map);

		Map<String, Object> requiredMap = new HashMap<String, Object>();
		requiredMap.put("否", "2");
		requiredMap.put("是", "1");
		model.addAttribute("requiredMap", requiredMap);

		Map<String, Object> primaryMap = new HashMap<String, Object>();
		primaryMap.put("否", "2");
		primaryMap.put("是", "1");
		model.addAttribute("primaryMap", primaryMap);
		return "field/update";
	}

 

### Thymeleaf 中 Radio Button 的数据绑定与回 在 Spring Boot Thymeleaf 集成的项目中,可以通过表单提交来实现 RadioButton 的数据绑定功能。以下是详细的说明以及示例代码。 #### 数据绑定原理 Thymeleaf 使用 `th:field` 属性将 HTML 表单字段与模型中的属性关联起来。对于 RadioButton 来说,`th:field` 会自动处理选中状态,并将其值绑定到对应的对象属性上[^1]。 #### 实现步骤详解 以下是一个完整的例子,展示如何通过 Thymeleaf 绑定并回 RadioButton 值: ##### 1. 创建实体类 定义一个简单的 Java 类用于存储用户的选择。 ```java public class UserPreferences { private String theme; // 可能的值:"light", "dark" public String getTheme() { return theme; } public void setTheme(String theme) { this.theme = theme; } } ``` ##### 2. 控制器逻辑 控制器负责向视图传递初始数据,并接收表单提交后的数据。 ```java @Controller @RequestMapping("/preferences") public class PreferencesController { @GetMapping public String showForm(Model model) { UserPreferences preferences = new UserPreferences(); preferences.setTheme("light"); // 默认主题设置为 light model.addAttribute("userPreferences", preferences); return "preferences"; } @PostMapping public String submitForm(@ModelAttribute UserPreferences userPreferences, Model model) { model.addAttribute("userPreferences", userPreferences); // 将更新后的偏好重新传入页面以便示 return "result"; // 跳转至结果页 } } ``` ##### 3. 视图模板 (HTML + Thymeleaf) 创建两个视图文件:一个是表单页面 (`preferences.html`),另一个是结果示页面 (`result.html`)。 ###### preferences.html 此页面包含 RadioButton 并允许用户选择其偏好的主题。 ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Preference Form</title> </head> <body> <form th:action="@{/preferences}" method="post" th:object="${userPreferences}"> <label><input type="radio" th:field="*{theme}" value="light"/> Light Theme</label><br/> <label><input type="radio" th:field="*{theme}" value="dark"/> Dark Theme</label><br/><br/> <button type="submit">Submit</button> </form> </body> </html> ``` 在此模板中,`th:field="*{theme}"` 自动绑定了 `UserPreferences` 对象的 `theme` 字段。当页面加载时,如果该字段已有默认值,则对应选项会被预先选中[^4]。 ###### result.html 此页面用来展示用户的最终选择。 ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Result Page</title> </head> <body> <h1>Your selected theme is:</h1> <p th:text="'You chose ' + ${userPreferences.theme}"></p> <a href="/preferences">Go back and change your preference.</a> </body> </html> ``` #### 关键点解析 - **`th:field`**: 它不仅实现了双向绑定,还能够根据当前模型的状态动态调整 DOM 元素的 checked 属性。 - **回机制**: 当表单被重新渲染时(例如 GET 请求或 POST 后重定向),已有的模型数据会再次填充到表单控件中[^3]。 --- ###
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值