我正在尝试使用 Spring Boot 重写我的配置繁重的普通 Spring MVC 项目。我使用 Spring Boot Initiaizer 在 IntelliJ 中启动了一个全新的 Spring Boot 项目,我将采用基于 Java 的最小配置的路线。很多教程都指出生成的默认主类就足够了,而且@SpringBootApplication
包括一切。我得到了一个示例 REST Controller 来工作并以 JSON 形式返回一个序列化对象,但事实证明,要显示一个 View 似乎很困难。我的结构如下,除了我创建的 webapps 目录之外的所有内容都是默认的。
src
`-main
`-java
`-resources
`-static
`-templates
`-webapp
`-WEB-INF
`-home.jsp
Controller 很简单。
@Controller
public class ViewMaster {
@RequestMapping("/home")
public String home() {
return "home";
}
}
没有任何配置,我想知道 Spring Boot 期望将 View 存储在哪里以及使用什么扩展名(html?)。我还尝试在
application.properties
中包含以下内容但我仍然收到 404 错误。在资源中移动 WEB-INF 目录或仅移动 html 文件也无济于事。spring.mvc.view.prefix=/WEB-INF/
spring.mvc.view.suffix=.jsp
我也试过在我的 pom.xml 中包含这些依赖项,但没有任何影响。
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
我一定在这里遗漏了一些非常明显的东西,所以如果有人能指出这一点,我们将不胜感激!
最佳答案
解决方案
我通过反复试验找到了答案,结果很烦人。如果这个结论是错误的,我希望有人能纠正我,但似乎 Spring Boot 不喜欢字符串 WEB-INF
.我重命名了 WEB-INF
目录到 view
并更改了 application.properties
到以下和 View 加载成功。
spring.mvc.view.prefix=/view/
spring.mvc.view.suffix=.jsp
其他发现
本练习的目标是创建一个 的工作示例。最小 , 基于 Java 的配置,所以我继续最小化设置。然后我发现在多个 SO 线程和论坛上提出的很多建议都没有帮助。 @JBNizet 在他对 Spring Boot 文档的评论中提供了一个链接,其中列出了一个没有人提到的非常重要的观点: JSP 不能很好地与 Spring Boot 配合使用,因为它具有取决于所选嵌入式容器的限制 .考虑到这一点,我决定尝试用 ThymeLeaf 模板替换 JSP。
我的新工作配置不需要这些:
application.properties
:spring.mvc.view.prefix
+ spring.mvc.view.suffix
org.springframework.boot / spring-boot-starter-tomcat
org.springframework.boot / tomcat-embed-jasper
javax.servlet / jstl
所以只是默认的 Spring Boot 模板和 2 个 ThymeLeaf 依赖项, View 名为
ViewName.html
放在 src/main/resources/templates
.<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
</dependency>
关于maven - 默认情况下,Spring Boot 期望 View 存储在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36100212/