【发布时间】:2021-04-06 05:33:09
【问题描述】:
我正在尝试找到一种更好的方法来为 thymeleaf 模板设置值,因为我觉得我这样做的方式是错误的。
假设我有一个带有两个映射的控制器:
@GetMapping("/")
public String getSearchPage(Model model) {
model.addAttribute("weatherRequest", new WeatherRequest());
model.addAttribute("weatherResponse", new WeatherResponse());
model.addAttribute("temperature_real");
model.addAttribute("temperature_feels");
model.addAttribute("humidity");
model.addAttribute("pressure");
return "index";
}
和
@PostMapping("/getWeather")
public String getWeatherForCity(@ModelAttribute("weatherRequest") WeatherRequest request, Model model) throws JsonProcessingException {
WeatherResponse response = weatherService.getWeatherData(request.getZipCode());
model.addAttribute("weatherResponse", new WeatherResponse());
model.addAttribute("temperature_real", response.mainWeatherData.temperature);
model.addAttribute("temperature_feels", response.mainWeatherData.temperatureFeels);
model.addAttribute("humidity", response.mainWeatherData.humidity);
model.addAttribute("pressure", response.mainWeatherData.pressure);
return "index";
@GetMapping("/") 用于我的主页,@PostMapping("/getWeather") 用于单击按钮时,以便我收集输入邮政编码的天气数据。
在我看来很奇怪,我添加了两次属性,但它确实有效。
但是,当我尝试更改模板以便仅在 mainWeatherData 不为空时呈现表单时,它不起作用。
您可以在下面找到相关的index.html 部分)。
这是index.html 中被更改的部分。
<div>
<form th:action="@{/getWeather}" method="post" th:object="${weatherRequest}">
<label>Enter the postal code:</label>
<input id="search" name="searchInput" th:field="*{zipCode}"/>
<button type="submit">Check weather</button>
</form>
<form >
<div>
<p>Temperature:<label th:text="${temperature_real}"></label></p>
<p>Feels like:<label th:text="${temperature_feels}"></label></p>
<p>Humidity:<label th:text="${humidity}"></label></p>
<p>Pressure:<label th:text="${pressure}"></label></p>
</div>
</form>
</div>
</body>
</html>
在我获取数据之前和mainWeatherData 不再为空之后,整个表单都不会呈现。
这是我添加到第二个表单以在天气数据不为空时呈现它:
<form th:if="${weatherResponse.mainWeatherData != null}">
- 主要问题:如何改进在控制器中添加属性。
- 第二个问题:当数据存在时,如何使其在 thymeleaf 中呈现形式。
【问题讨论】:
标签: java html spring-boot mapping thymeleaf