【发布时间】:2020-08-25 16:22:26
【问题描述】:
经过数小时阅读不同的帖子、示例项目和许多不同的修复后,我解决了与在我的 Spring Boot 项目中提供静态内容相关的问题 - 特别是我从 html 页面中的 CSS 链接收到的错误。在以下链接(以下摘录)中为我解决了这个问题的两个答案中不太受欢迎的答案。
检查使用注解的控制器类 - @RestController 或 @Controller。不要在一个类中混合使用 Rest API 和 MVC 行为。对于 MVC,使用 @Controller,对于 REST API,使用 @RestController
Spring Boot app not serving static content
总之,在我尝试了一切(修改 application.properties 以显式设置静态目录路径,将 CSS 文件移动到许多不同的文件夹中,包括假定的标准集的文件夹)之后,找不到样式表。但是...将@RestController 换成@Controller 解决了以下代码。
@Controller
public class MVCController {
@Autowired
ThingdefstatsviewRepository defstatviewRepository;
@Autowired
ThingDefRecord thingDefRecord;
@GetMapping(path="/characterdef/{defid}")
public ModelAndView thymeLeafCharacterDefByID(@PathVariable String defid) {
Long id = Long.parseLong(defid);
thingDefRecord.loadAllStats(id);
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("CharacterPage.html");
//Adds an attribute to the model as a name/value(object) pair
modelAndView.addObject("thingstats", thingDefRecord);
return modelAndView;
}
}
问题是,为什么?在 @RestController 类中使用 ModelAndView 对象会阻止我的 html 页面加载 CSS 文件是怎么回事?或者反过来,简单地使用@Controller 让它立即工作的原因是什么?
显然,作为 Spring 的新手,我错过了有关这些不同控制器如何与链接的静态内容一起工作的一些信息,但无法找出原因。
【问题讨论】:
-
也许这可以帮助你:spring-controller-vs-restcontroller
标签: css spring-boot model-view-controller static thymeleaf