thymeleaf实现input输⼊框有默认值1. 使⽤场景
前台form表格数据是个对象,input输⼊框⾥⽤户没有输⼊值时,添加个默认值
2. 实现
2.1 后台代码
Domain
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Elems {
private String defaultsMap_evaluationMethod;
}
Controller
@GetMapping("/pros")
public ModelAndView prosInterface(HttpServletRequest request, @ModelAttribute(name = "elems") Elems elems) {        ModelAndView mav = new ModelAndView("pros");
mav.addObject("elems",elems);
return mav;
}
2.2 thymeleaf代码
<!doctype html>
<html lang="en" xmlns:th="">
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" href="/css/bootstrap.min.css">
<link rel="stylesheet" href="/css/cal.css">
<script src="/js/jquery-3.4.1.slim.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
<title>Quotation Calculate</title>
<style>
body {
padding-top: 40px;
padding-bottom: 10px;
}
</style>
</head>
<body>
<div class="container ">
<form th:method="get" th:object="${elems}" th:action="@{~/tool/pros}">
<label >defaultsMap</label>
<table>
<tr>
<td>defaultsMap_evaluationMethod</td>
<td>
<input type="text" th:value="*{defaultsMap_evaluationMethod == null ? 'Commercial Price Guidance' : defaultsMap_evaluationMethod}" name ="defaultsMap_evaluationMethod" th:onclick="(this.value='')"/>
</td>
</tr>
</table>
<button th:type="submit">calculate pros</button>thymeleaf用法
</form>
</div>
</body>
</html>
关键点
<input type="text" th:value="*{defaultsMap_evaluationMethod == null ? 'Commercial Price Guidance' : defaultsMap_evaluationMethod}" name="defaultsMa p_evaluationMethod" th:onclick="(this.value='')"/>
使⽤时有个⼩bug,困扰我好久,当我使⽤:
<input type="text" th:value="*{defaultsMap_evaluationMethod == null ? 'Commercial Price Guidance' : defaultsMap_evaluationMethod}" th:field="*{defaults Map_evaluationMethod}" th:onclick="(this.value='')"/>
在input标签中,th:field标签和value⼀起使⽤时,value标签竟然不能⽤,没有默认值了。好神奇。最后改⽤基本标签name='对象字段名’就可以了~~真是神奇的存在!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。