前后端交互常用组件
推荐网站
https://www.w3school.com.cn/tags/tag_select.asp
下拉框
默认就是第一个
<select name="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat" selected="selected">Fiat</option>
<option value="audi">Audi</option>
</select>
SPring boot绑定下拉框
实现可以从后端获取下拉框的默认值
<div class="mb-3">
<label for="sex" class="form-label">sex</label>
<select class="form-select" name="sex" id="sex" th:value="${user.sex} ">
<option value="男" >男</option>
<!-- 关键 -->
<option value="女" th:selected="${user.sex=='女'}">女</option>
<!-- 关键 -->
</select>
日期/时间/日期和时间选择器
只需要更改输入框的类型即可
日期和时间
<input type="datetime-local" id="meeting-time"
name="meeting-time" value="2018-06-12T19:30"
min="2018-06-07T00:00" max="2018-06-14T00:00">
精确到秒
只需要添加属性step="1",即可精确到秒
<input type="datetime-local" step="1" class="form-control" name="localTimez" th:id="localTimez" >
问题:格式不对
默认格式是:yyyy-MM-ddTHH:mm
和常用格式(java.util.Date)不一样,因此需要在后端进行格式转化
config
package com.sdut20110506064.test2.config;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
public class TimeConfig {
public Date datetimeToDate(String time) {
System.out.println(time+" 前台传过来的时间");
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//如果显秒
LocalDateTime localDateTime = LocalDateTime.parse(time.replaceAll("T", " ") , df);
//如果不显秒
//LocalDateTime localDateTime = LocalDateTime.parse(time.replaceAll("T", " ") + ":00", df);
System.out.println(localDateTime+" localDateTime格式的时间");
Date date = Date.from( localDateTime.atZone( ZoneId.systemDefault()).toInstant());
System.out.println(date+" Date格式的时间(java.util的包)");
return date;
}
}
Controller
@RequestMapping("/insertUser")
public String InsertUser(Model model,User user,String time) throws Exception {
TimeConfig timeConfig = new TimeConfig();
Date date = timeConfig.datetimeToDate(time);
user.setBirthday(date);
//写入数据库
int flag = userMapper.insertUser(user);
model.addAttribute("flag",flag);
return "redirect:index";
}
HTML
<div>
<label for="time" >birthday</label>
<div>
<!-- <input id="time" type="datetime-local">-->
<input type="datetime-local" step="1" name="time" id="time" />
</div>
</div>
日期:date
<input type="date" name="start_time" value="" />
时间:time
<input type="time" name="start_time" value="" />