我想从服务读取数据到 Controller 并在 Spring boot 上显示在 UI 上,但出现以下错误
ERROR 20984 --- [nio-8080-exec-2] s.e.ErrorMvcAutoConfiguration$StaticView : Cannot render error page for request [/countries] as the response has already been committed. As a result, the response may have the wrong status code.
数据库还有以下数据
mysql> 从国家中选择*;
+----+-------------+------+---------------+---------------+-------------+
| id | capital | code | continent | description | nationality |
+----+-------------+------+---------------+---------------+-------------+
| 1 | Washington | 01 | North America | United States | American |
| 2 | Addis Ababa | 01 | Africa | Ethiopia | Ethiopian |
+----+-------------+------+---------------+---------------+-------------+
型号
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class Country {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String code;
private String capital;
private String description;
private String nationality;
private String continent;
@OneToMany(mappedBy="country")
private List<State> states;
}
存储库
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.kindsonthegenius.FleetApp.models.Country;
@Repository
public interface CountryRepository extends JpaRepository<Country, Integer> {
}
服务
@Service
public class CountryService {
@Autowired
private CountryRepository countryRepository;
public List<Country> getCountries(){
return countryRepository.findAll();
}
}
Controller
@Controller
public class CountryController {
@Autowired
private CountryService countryService;
@GetMapping("/countries")
public String goCountry(Model model) {
List<Country> countryList = countryService.getCountries();
model.addAttribute("countries", countryList);
return "country";
}
}
用户界面
<table class="table">
<thead>
<tr>
<th scope="col">id</th>
<th scope="col">Description</th>
<th scope="col">Capital</th>
</tr>
</thead>
<tbody>
<tr th:each="country : ${countries}">
<td th:text="${country.id}"></td>
<td th:text="${country.description}"></td>
<td th:text="${country.capital}"></td>
</tr>
</tbody>
</table>
请帮我修复此错误?
最佳答案
我猜这是因为国家和州之间的 @OneToMany 关系而发生的。如果您分享您的“状态”模型,我可以告诉您要更改哪些内容。 然而,当国家加载了州并且州中也有国家时,通常会发生此错误。这将创建无限的 JSON 树。检查此链接 Springboot Hibernate One to Many infinty recursion
关于java - 无法呈现请求 [/countries] 的错误页面,因为响应已提交。因此,响应可能有错误的状态代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73424809/