Olá pessoal! Estou com um probleminha apenas em uma página...
Utilizando o Spring MVC e Java com MySQL, fiz um crud para cadastrar componentes e funcionou perfeitamente:
![image|690x387](upload://8Y4MrB8lp4cGLJemhZkfwKJ6cuu.png)
Tentei fazer um igual para cadastrar uma lista de fabricantes, o cadastro em banco funciona, mas não exibe nada na lista do navegador. O interessante é que a lista é retornada normalmente no console do Eclipse:
![image|690x242](upload://sKigwft8nLI0xp4iTdQLiWNUTzc.png)
Abaixo, o código das classes:
model.fabricante.java
package br.com.kmacedo.carcare.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "fabricante")
public class Fabricante {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long idfabricante;
@Column(name = "fabricanteDescricao")
private String fabricanteDescricao;
public long getIdfabricante() {
return idfabricante;
}
public void setIdfabricante(long idfabricante) {
this.idfabricante = idfabricante;
}
public String getFabricanteDescricao() {
return fabricanteDescricao;
}
public void setFabricanteDescricao(String fabricanteDescricao) {
this.fabricanteDescricao = fabricanteDescricao;
}
}
service.FabricanteService
package br.com.kmacedo.carcare.service;
import java.util.List;
import org.springframework.data.domain.Page;
import br.com.kmacedo.carcare.model.Fabricante;
public interface FabricanteService {
List<Fabricante> getAllFabricantes();
void saveFabricante(Fabricante fabricante);
Fabricante getFabricanteById(long id);
void deleteFabricanteById(long id);
Page<Fabricante> findPaginated(int pageNo, int PageSize, String sortField, String sortDirection);
}
> Bloco de Citação
Repository.FabricanteRepository
package br.com.kmacedo.carcare.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import br.com.kmacedo.carcare.model.Fabricante;
@Repository
public interface FabricanteRepository extends JpaRepository<Fabricante, Long> {
}
Service.FabricanteServiceImpl
package br.com.kmacedo.carcare.service;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import br.com.kmacedo.carcare.model.Fabricante;
import br.com.kmacedo.carcare.repository.FabricanteRepository;
@Service
public class FabricanteServiceImpl implements FabricanteService{
@Autowired
private FabricanteRepository fabricanteRepository;
@Override
public List<Fabricante> getAllFabricantes() {
return fabricanteRepository.findAll();
}
@Override
public void saveFabricante(Fabricante fabricante) {
this.fabricanteRepository.save(fabricante);
}
@Override
public Fabricante getFabricanteById(long id) {
Optional<Fabricante> optional = fabricanteRepository.findById(id);
Fabricante fabricante = null;
if (optional.isPresent()) {
fabricante = optional.get();
} else {
throw new RuntimeException(" Fabricante not found for id :: " + id);
}
return fabricante;
}
@Override
public void deleteFabricanteById(long id) {
this.fabricanteRepository.deleteById(id);
}
@Override
public Page<Fabricante> findPaginated(int pageNo, int pageSize, String sortField, String sortDirection) {
Sort sort = sortDirection.equalsIgnoreCase(Sort.Direction.ASC.name()) ? Sort.by(sortField).ascending():
Sort.by(sortField).descending();
Pageable pageable = PageRequest.of(pageNo - 1, pageSize, sort);
return this.fabricanteRepository.findAll(pageable);
}
}
Controller.FabricanteController
package br.com.kmacedo.carcare.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import br.com.kmacedo.carcare.service.FabricanteService;
import br.com.kmacedo.carcare.model.Fabricante;
@Controller
public class FabricanteController {
@Autowired
private FabricanteService fabricanteService;
// display list of fabricantes
@GetMapping("/fabricantes")
public String viewFabricantePage(Model model) {
return findPaginated(1, "idfabricante", "asc", model);
}
@GetMapping("/showNewFabricanteForm")
public String showNewFabricanteForm(Model model) {
// create model attribute to bind form data
Fabricante fabricante = new Fabricante();
model.addAttribute("fabricante", fabricante);
return "new_fabricante";
}
@PostMapping("/saveFabricante")
public String saveFabricante(@ModelAttribute("fabricante") Fabricante fabricante) {
// save fabricante to database
fabricanteService.saveFabricante(fabricante);
return "redirect:/fabricantes";
}
@GetMapping("/showFormFabricanteForUpdate/{id}")
public String showFormFabricanteForUpdate(@PathVariable ( value = "id") long id, Model model) {
// get fabricante from the service
Fabricante fabricante = fabricanteService.getFabricanteById(id);
// set fabricante as a model attribute to pre-populate the form
model.addAttribute("fabricante", fabricante);
return "update_fabricante";
}
@GetMapping("/deleteFabricante/{id}")
public String deleteFabricante(@PathVariable (value = "id") long id) {
// call delete fabricante method
this.fabricanteService.deleteFabricanteById(id);
return "redirect:/fabricantes";
}
@GetMapping("/pageFabricantes/{pageNo}")
public String findPaginated(@PathVariable (value = "pageNo") int pageNo,
@RequestParam("sortField") String sortField,
@RequestParam("sortDir") String sortDir,
Model model) {
int pageSize = 5;
Page<Fabricante> page = fabricanteService.findPaginated(pageNo, pageSize, sortField, sortDir);
List<Fabricante> listFabricantes = page.getContent();
model.addAttribute("currentPage", pageNo);
model.addAttribute("totalPages", page.getTotalPages());
model.addAttribute("totalItems", page.getTotalElements());
model.addAttribute("sortField", sortField);
model.addAttribute("sortDir", sortDir);
model.addAttribute("reverseSortDir", sortDir.equals("asc") ? "desc" : "asc");
model.addAttribute("listComponentes", listFabricantes);
return "fabricantes";
}
}
fabricantes.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>CarCare - Controle de manutenção</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
crossorigin="anonymous">
</head>
<body>
<div class="container my-2">
<h1>Lista de fabricantes</h1>
<a th:href = "@{/showNewFabricanteForm}" class="btn btn-primary btn-sm mb-3"> Adicionar fabricante </a>
<a th:href = "@{/}" class="btn btn-primary btn-sm mb-3"> Voltar para página inicial </a>
<table border="1" class = "table table-striped table-responsive-md">
<thead>
<tr>
<th>
<a th:href="@{'/pageFabricante/' + ${currentPage} + '?sortField=fabricanteDescricao&sortDir=' + ${reverseSortDir}}">
Fabricante</a>
</th>
<th> Ações </th>
</tr>
</thead>
<tbody>
<tr th:each="fabricante : ${listFabricantes}">
<td th:text="${fabricanteDescricao}"></td>
<td> <a th:href="@{/showFormFabricanteForUpdate/{id}(id=${fabricante.idfabricante})}" class="btn btn-primary">Update</a>
<a th:href="@{/deleteFabricante/{id}(id=${fabricante.idfabricante})}" class="btn btn-danger">Delete</a>
</td>
</tr>
</tbody>
</table>
<div th:if = "${totalPages > 1}">
<div class = "row col-sm-10">
<div class = "col-sm-2">
Total Rows: [[${totalItems}]]
</div>
<div class = "col-sm-1">
<span th:each="i: ${#numbers.sequence(1, totalPages)}">
<a th:if="${currentPage != i}" th:href="@{'/pageFabricante/' + ${i}+ '?sortField=' + ${sortField} + '&sortDir=' + ${sortDir}}">[[${i}]]</a>
<span th:unless="${currentPage != i}">[[${i}]]</span>
</span>
</div>
<div class = "col-sm-1">
<a th:if="${currentPage < totalPages}" th:href="@{'/pageFabricante/' + ${currentPage + 1}+ '?sortField=' + ${sortField} + '&sortDir=' + ${sortDir}}">Next</a>
<span th:unless="${currentPage < totalPages}">Next</span>
</div>
<div class="col-sm-1">
<a th:if="${currentPage < totalPages}" th:href="@{'/pageFabricante/' + ${totalPages}+ '?sortField=' + ${sortField} + '&sortDir=' + ${sortDir}}">Last</a>
<span th:unless="${currentPage < totalPages}">Last</span>
</div>
</div>
</div>
</div>
</body>
</html>
Desde já, meu muito obrigado.