英文:
Thymleaf not returning templates but strings
问题
我正在使用Thymeleaf构建一个应用程序,遇到了一个问题。例如,当我返回一个模板时,比如 return "products";
,当我访问在 @GetMapping()
中指定的URL 时,我得到了字符串 "products",而不是渲染的模板。
@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 "products";
... and when I visit the url i addressed in @GetMapping()
i get the string "products" instead of rendered template
@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);
}
}
答案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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论