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="http://www.thymeleaf.org">
<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 style="background-color: red">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>
</form>
</div>
</body>
</html>
关键点
<input type="text" th:value="*{defaultsMap_evaluationMethod == null ? 'Commercial Price Guidance' : defaultsMap_evaluationMethod}" name="defaultsMap_evaluationMethod" th:onclick="(this.value='')"/>
使用时有个小bug,困扰我好久,当我使用:
<input type="text" th:value="*{defaultsMap_evaluationMethod == null ? 'Commercial Price Guidance' : defaultsMap_evaluationMethod}" th:field="*{defaultsMap_evaluationMethod}" th:onclick="(this.value='')"/>
在input标签中,th:field标签和value一起使用时,value标签竟然不能用,没有默认值了。好神奇。最后改用基本标签name='对象字段名’就可以了~~真是神奇的存在!