代码之家  ›  专栏  ›  技术社区  ›  Mohammed Haydar

如何在另一个html页面中访问spring模型的数据?

  •  0
  • Mohammed Haydar  · 技术社区  · 3 年前

    PlaceController。Java语言

    @GetMapping("/places")
        public String listPlaces(Model model, HttpSession session) {
            //keys and values , access this key using thymeleaf syntax ${listPlaces}
            model.addAttribute("listPlaces", placeService.getAllPlaces());
            return "place/places";
        }
    

    我需要从places获取listPlaces数据。要索引的html。html我试图创建会话,但无法从索引页调用它

                <tbody>
                    <tr  th:each="place: ${listPlaces}" >
                        <td th:text="${place.place_id}">Place Id</td>
                        <td th:text="${place.name}">Place Name</td>
                        <td th:text="${place.city_name}">City Name</td>
                        <td th:text="${place.description}">Place Description</td>
                        <td th:text="${place.longitude}">Place Longitude</td>
                        <td th:text="${place.latitude}">Place Latitude</td>
                        <td><img th:src="${'data:image/png;charset=utf-8;base64,' + place.byteToString(place.image)}" height="150px" width="150px" alt="img"></td>
                        <td th:text="${place.category}">Place Category</td>
                        <td>
                            <a th:href="@{/places/edit/{id}(id=${place.place_id})}" class="btn btn-primary">Update</a>
                            <a th:href="@{/places/{id}(id=${place.place_id})}" class="btn btn-danger">Delete</a>
                        </td>
                    </tr>
                </tbody>
            </table>
    
    2 回复  |  直到 3 年前
        1
  •  1
  •   Mohammed Haydar    3 年前

    我在控制器索引中添加了一个带有listPlaces的模型属性。html

     @RequestMapping("/index")
        public String index(Model model) {
            model.addAttribute("listP", placeService.getAllPlaces());
            return "index";
        }
    

    然后我在索引中使用。html

    <script th:inline="javascript">
            /*<![CDATA[*/
            // Initialize and add the map
            function initMap() {
                var places = [[${listP}]];
    </script>
    

    贷项至 boris-ivanov

        2
  •  0
  •   Valerij Dobler    3 年前

    我想你在问两件事。

    1. 如何返回两个端点的相同位置?
    2. 如何在我所有的位置上重复使用桌子?

    第一个问题的答案是使用IndexController,它以与PlaceController相同的方式填充模型。您可以创建CommonAttributeService,它可以提供一种方法来填充公共属性,如下所示:

    @Service
    public class CommonAttributesService
    {
        private PlaceService placeService;
        public CommonAttributesService(PlaceService placeService)
        {
            this.placeService = placeService;
        }
    
        public void fillCommonAttributes(Model model)
        {
            model.addAttribute("listPlaces", placeService.getAllPlaces());
        }
    }
    

    这样,就不需要复制逻辑。

    第二个问题的答案是 thymeleaf templates