【问题标题】:redirect to HTML page using spring boot / thymyleaf使用 spring boot / thymeleaf 重定向到 HTML 页面
【发布时间】:2021-09-16 02:25:45
【问题描述】:

这是我的控制器:

@RestController
public class GraphController {

    @GetMapping("/displayBarGraph")
    public String barGraph(Model model) {
        Map<String, Integer> surveyMap = new LinkedHashMap<>();
        surveyMap.put("Java", 40);
        surveyMap.put("Dev oops", 25);
        surveyMap.put("Python", 20);
        surveyMap.put(".Net", 15);
        model.addAttribute("surveyMap", surveyMap);
        return "barGraph";
    }

    @GetMapping("/displayPieChart")
    public String pieChart(Model model) {
        model.addAttribute("pass", 50);
        model.addAttribute("fail", 50);
        return "pieChart";
    }

这是我的file.proprieties

spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.enabled=false

spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.html

这些是我的 HTML 文件:

但它总是像这样重定向我:

请问有什么解决办法吗?

【问题讨论】:

    标签: java spring spring-boot spring-mvc thymeleaf


    【解决方案1】:
    1. spring.thymeleaf.enabled 设置为 false 会禁用 Spring MVC/Web 的 Thymeleaf。因此,控制器只返回 Thymeleaf 模板的名称,而不是通过 Thymeleaf 视图解析。

      要解决此问题,请删除 spring.thymeleaf.enabled 属性或将其设置为 true,即 Thymeleaf 自动配置的 default

      spring.thymeleaf.enabled=true
      
    2. 使用模板引擎时使用@Controller 而不是@RestController,并且您不希望将返回值绑定到响应正文:

      @Controller
      public class GraphController {
      
          @GetMapping("/displayBarGraph")
          public String barGraph(Model model) {
              // ...
              return "barGraph";
          }
      
          // ...
      }
      
    3. 您配置的模板路径需要与存储模板的实际路径相匹配。所以要么更改 setspring.thymeleaf.prefix=classpath:/template/ template 目录重命名为 templates

    4. 从您的配置中删除两个属性 spring.mvc.view.prefixspring.mvc.view.suffix。如果您想使用 JSP,这将是必要的。

    【讨论】:

      【解决方案2】:

      重命名

      src/main/resources/template

      文件夹到

      src/main/resources/templates

      文件夹名称中缺少“s”。

      【讨论】:

        【解决方案3】:

        为了使这项工作正常进行的一些更改。

        1. 将@RestController 更改为@Controller,使其返回页面而不是正文中的响应。

        2. 将文件夹重命名为模板或更改视图解析器的属性文件中的路径。

        3. 不需要启用 thymeleaf 的属性。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-09-10
          • 1970-01-01
          • 1970-01-01
          • 2016-09-12
          • 2020-05-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多