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";
}
I need to get the listPlaces data from places.html to index.html I tried to create session but yet I can't call it from the index page
<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})}" >Update</a>
<a th:href="@{/places/{id}(id=${place.place_id})}" >Delete</a>
</td>
</tr>
</tbody>
</table>
CodePudding user response:
I think you are asking two things.
- How to return the same places for two endpoints?
- How to reuse the table with all my places?
The answer to the first question is to have an IndexController, which fills the model the same way as the PlaceController does. You could create an CommonAttributesService, which could provide a method to fill common attributes as follows:
@Service
public class CommonAttributesService
{
private PlaceService placeService;
public CommonAttributesService(PlaceService placeService)
{
this.placeService = placeService;
}
public void fillCommonAttributes(Model model)
{
model.addAttribute("listPlaces", placeService.getAllPlaces());
}
}
This way, you don't need to duplicate the logic.
And the asnwer to the second question is to use thymeleaf templates.
CodePudding user response:
I have added a Model Attribute with a listPlaces in the controller index.html
@RequestMapping("/index")
public String index(Model model) {
model.addAttribute("listP", placeService.getAllPlaces());
return "index";
}
Then I used in index.html
<script th:inline="javascript">
/*<![CDATA[*/
// Initialize and add the map
function initMap() {
var places = [[${listP}]];
</script>
credits to boris-ivanov