【问题标题】:Thymeleaf and Spring Boot - adding attributes to the model. What is the correct way?Thymeleaf 和 Spring Boot - 为模型添加属性。正确的方法是什么?
【发布时间】: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 不再为空之后,整个表单都不会呈现。

这是我添加到第二个表单以在天气数据不为空时呈现它:

&lt;form th:if="${weatherResponse.mainWeatherData != null}"&gt;

  • 主要问题:如何改进在控制器中添加属性。
  • 第二个问题:当数据存在时,如何使其在 thymeleaf 中呈现形式。

【问题讨论】:

    标签: java html spring-boot mapping thymeleaf


    【解决方案1】:

    你的感觉没有错。您尝试编写的示例还有一些更有用的方法,我将向您展示我的简单而流行的用法:

    public class WeatherRequest {
    
        private String zipCode;
    
        public WeatherRequest() {
        }
    
        // getter / setter ..
    }
    
    public class WeatherResponse {
    
        private String temperatureReal;
        private String temperatureFeels;
        private String humidity;
        private String pressure;
    
        public WeatherResponse() {
        }
    
        // getter/setter ..
    }
    
    @Controller
    public class WeatherController {
    
       @GetMapping("/")
       public String getSearchPage(Model model) {
          model.addAttribute("weatherRequest", new WeatherRequest());
          return "weather-search";
       }
    
       @PostMapping("/getWeather")
       public String getWeatherForCity(Model model, WeatherRequest weatherRequest) {
          model.addAttribute("weatherRequest", weatherRequest);
          model.addAttribute("weatherResponses", getWeatherResponse(weatherRequest.getZipCode()));
          return "weather-search";
       }
    
       private List<WeatherResponse> getWeatherResponses(String zipCode) {
          List<WeatherResponse> weatherResponses = new ArrayList<>();
          for (int i = 1; i < 3; i++) {
             WeatherResponse weatherResponse = new WeatherResponse();
             weatherResponse.setTemperatureReal("A" + i + ": " + zipCode);
             weatherResponse.setTemperatureFeels("B" + i + ": " + zipCode);
             weatherResponse.setHumidity("C" + i + ": " + zipCode);
             weatherResponse.setPressure("D" + i + ": " + zipCode);
             weatherResponses.add(weatherResponse);
          }
          return weatherResponses;
       }
    }
    
    <!DOCTYPE HTML>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <body>
        <form th:action="@{/getWeather}" method="post" th:object="${weatherRequest}">
            <label>Enter the postal code:</label>
            <input th:field="*{zipCode}" />
            <button type="submit">Check Weather</button>
        </form>
        <div th:if="${!weatherResponses.isEmpty()}">
            <div th:each="weatherResponse: ${weatherResponses}">
                <p>Temperature:<label th:text="${weatherResponse.temperatureReal}"></label></p>
                <p>Feels Like:<label th:text="${weatherResponse.temperatureFeels}"></label></p>
                <p>Humidity:<label th:text="${weatherResponse.humidity}"></label></p>
                <p>Pressure:<label th:text="${weatherResponse.pressure}"></label></p>
            </div>
        </div>
    </body>
    </html>
    

    在 Thymeleaf 中,迭代是通过使用 th:each 属性来实现的。

    你可以走得更远。例如,当您点击搜索时,您可以发出 Ajax 请求并立即更新结果等。

    如果您使用Ajax请求,则不需要getWeatherForCity()方法中的weatherRequest

    此示例链接将展示如何利用 Thymeleaf Fragments 重用网站的一些常见部分:

    【讨论】:

      猜你喜欢
      • 2016-07-12
      • 2018-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多