繁体   English   中英

无法从 Spring-Boot 控制器呈现 thymleaf 页面。 只打印输出中的返回字符串

[英]Unable to render thymleaf page from Spring-Boot controller. Prints only the return string in output

问题:我开发了一个 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";
}
}

这是我的Thymleaf页面productsList.html

<!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 页面。 但不是这个页面。

那是因为您在控制器之上使用了@RestController 注释,它只不过是@Controller+@ResponseBody。

尝试仅使用 @Controller,然后根据您的方法专门使用 @ResponseBody。

例如 。 如果要返回 json 响应正文,请在方法上使用 @ResponseBody。

如果要呈现 thymeleaf 页面,请不要使用@ResponseBody。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM