问题描述
问题:我已经开发了Spring-Boot rest api,可以从POSTMAN调用它。 现在,我从thymleaf页面请求相同的REST API方法。但是它仅呈现一个字符串。实际页面未加载。.
这是我的控制器:
@RestController
@RefreshScope
@RequestMapping("/shopping")
public class ShoppingController {
@RequestMapping(value="/productList")
public String listAllProducts(ModelMap model){
logger.info("ShoppingMS : listAllProducts()");
ResponseEntity<List<Product>> responseProductList = prodServ.listAllProducts();
List<Product> products = responseProductList.getBody();
if(products.isEmpty()) {
logger.info("No Products Found");
}
logger.info("No of products fetched : " +products.size());
model.addAttribute("products",products);
return "productList";
}
}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
<Meta charset="UTF-8">
<title>Product List</title>
<link rel="stylesheet" type="text/css" th:href="@{/css/styles.css}">
</head>
<body>
<th:block th:include="/_header"></th:block>
<th:block th:include="/menu"></th:block>
<div class="page-title">Product List</div>
<div class="product-preview-container"
th:each="prodInfo : ${products.list}">
<ul>
<li>Product Code: <span th:utext="${prodInfo.productCode}"></span></li>
<li>Product Name: <span th:utext="${prodInfo.productName}"></span></li>
<li>Product Price: <span th:utext="${#numbers.formatDecimal(prodInfo.productPrice,3,2,'COMMA')}"></span></li>
<li><a th:href="@{|/buyProduct?code=${prodInfo.code}|}">Buy Now</a></li>
</ul>
</div>
<br />
<div class="page-navigator">
<th:block th>
<a th:href="@{|/productList|}" class="nav-item"></a>
<span class="nav-item" > ... </span>
</th:block>
</div>
<th:block th:include="/_footer"></th:block>
</body>
</html>
对thymleaf的Maven依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
项目结构图:
输出:
Calling URL : http://localhost:1000/shopping/productList
It returns only the string `productList` in the page.
请告诉我我在哪里做错了。我能够呈现index.html页面。但不是此页面。
更新:我已经在我的Rest Controller类上提供了我正在使用的Maven依赖关系和使用的注释。
解决方法
我相信你也是
- 缺少
spring-boot-starter-thymeleaf
依赖性。此依赖项包含对百里香模板解析器(将类型字符串返回为html模板名称)和实际呈现所必需的依赖项和自动配置。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
- 或在控制器类中使用@Controller而不是@RestController。 @RestController默认返回json响应。对于模板渲染,您应该使用@Controller。
答案:
使用@Controller
代替@RestController
解决了该问题。能够立即呈现html页面。