Thymeleaf未返回模板而是字符串。

huangapple go评论57阅读模式
英文:

Thymleaf not returning templates but strings

问题

我正在使用Thymeleaf构建一个应用程序,遇到了一个问题。例如,当我返回一个模板时,比如 return "products";,当我访问在 @GetMapping() 中指定的URL 时,我得到了字符串 "products",而不是渲染的模板。

Thymeleaf未返回模板而是字符串。.

Thymeleaf未返回模板而是字符串。

@Service
public class HomeService {

    @Autowired
    ProductRepository productRepository;

    public String getProducts(Model model) {
        List<Product> products = productRepository.findAll();

        if (!products.isEmpty()) {
            model.addAttribute("product", products);
            return "products";
        } else {
            return "404";
        }
    }
}

@RestController
public class HomeController {

    @Autowired
    HomeService homeService;

    @GetMapping("/home")
    public String home(Model model) {
        return homeService.getProducts(model);
    }
}
英文:

I'm building an application with thymeleaf, and i've encountered this problem where when returning a template as for example ...return &quot;products&quot;;... and when I visit the url i addressed in @GetMapping() i get the string "products" instead of rendered template

Thymeleaf未返回模板而是字符串。.

Thymeleaf未返回模板而是字符串。

@Service
public class HomeService {

    @Autowired
    ProductRepository productRepository;

    public String getProducts(Model model) {
        List&lt;Product&gt; products= productRepository.findAll();

        if (!products.isEmpty()){
            model.addAttribute(&quot;product&quot;, products);
            return &quot;products&quot;;
        }else{
            return &quot;404&quot;;
        }
    }
}

@RestController
public class HomeController {

    @Autowired
    HomeService homeService;

    @GetMapping(&quot;/home&quot;)
    public String home(Model model){
        return homeService.getProducts(model);
    }
}

答案1

得分: 2

如上所述,@RestController注解应该替换为@Controller注解。

在Spring中,@RestController注解旨在构建返回JSON或XML格式数据的REST Web服务,不支持使用视图模板引擎如Thymeleaf。如果您想渲染HTML视图,应该使用@Controller。在@Controller中,我们可以在Spring Web MVC中返回视图。

英文:

As stated above, the @RestController annotation should be replaced with the @Controller annotation.

The @RestController annotation in Spring is designed for building REST web services that return data in JSON or XML format, and it does not support the use of view templating engines like Thymeleaf. If you want to render HTML views, you should use the @Controller. In @Controller, we can return a view in Spring Web MVC.

答案2

得分: 0

使用 @Controller,@RestController 仅适用于 RestAPI,不适用于 MVC。

英文:

Use @Controller, @RestController is for RestAPI only, and not MVC

huangapple
  • 本文由 发表于 2023年2月19日 04:39:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75496257.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定