springboot 无法解析 MVC 视图

问题描述:
@RequestMapping返回视图的时候一直报错:无法解析 MVC 视图 “index”
在这里插入图片描述
原因:
无法解析是因为找不到拼接的前后缀,所以无法跳转。忘记导入模板引擎依赖

解决:
在pom中下增加依赖

    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf-spring5</artifactId>
    </dependency>
    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-java8time</artifactId>
    </dependency>
### Spring Boot 中视图解析器的配置方法 #### 1. 使用内置视图解析器 `InternalResourceViewResolver` 配置 JSP 在 Spring Boot 中,默认情况下并不推荐使用 JSP,因为其与内嵌 Tomcat 的兼容性有限。如果确实需要使用 JSP,则可以通过以下方式实现: - **引入必要的依赖项** 为了使 Spring Boot 支持 JSP 解析,需添加如下 Maven 依赖[^4]: ```xml <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> </dependency> ``` - **配置视图解析器** 通过修改 `application.properties` 文件来指定前缀和后缀[^4]: ```properties spring.mvc.view.prefix=/WEB-INF/jsp/ spring.mvc.view.suffix=.jsp ``` 此配置表示所有的控制器返回值将以 `/WEB-INF/jsp/` 开头并以 `.jsp` 结束。 --- #### 2. 配置 FreeMarker 模板引擎作为视图解析器 FreeMarker 是一种流行的模板引擎,在 Spring Boot 中可以轻松集成它。以下是具体步骤: - **引入 FreeMarker 依赖** 在项目的 `pom.xml` 文件中加入以下内容[^2]: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> ``` - **设置 FreeMarker 属性** 编辑 `application.properties` 或 `application.yml` 来定义模板路径及文件扩展名[^2]: ```properties spring.freemarker.template-loader-path=classpath:/templates/ spring.freemarker.suffix=.ftl ``` 这会告诉 Spring Boot 将模板存储于类路径下的 `templates` 文件夹中,并且所有模板都应以 `.ftl` 扩展结束。 --- #### 3. 配置 Thymeleaf 模板引擎作为视图解析器 Thymeleaf 是另一种广泛使用的现代 HTML 模板引擎,适合动态 Web 应用程序开发。下面是如何将其应用于 Spring Boot: - **引入 Thymeleaf 依赖** 确保项目中的 `pom.xml` 包含以下条目[^3]: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> ``` - **调整 Thymeleaf 设置** 同样地,更新 `application.properties` 文件以便自定义行为: ```properties spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html spring.thymeleaf.cache=false ``` 这里设置了模板位置以及它们应该具有的扩展名为 `.html`;还禁用了缓存机制方便调试阶段即时查看更改效果。 --- #### 示例代码展示如何创建 Controller 并配合视图解析工作流程 假设已经完成了上述任意一种类型的视图解析器设定操作之后,就可以编写简单的控制层逻辑测试渲染情况了。比如基于 Thymeleaf 实现的一个例子可能看起来像这样: ```java import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @Controller public class HelloController { @GetMapping("/hello") public String hello(Model model){ model.addAttribute("message", "Hello, world!"); return "index"; // 返回 index.html 页面名称 (无需加 .html 后缀) } } ``` 当访问 `/hello` 路径时,该 controller 方法会被触发并将数据传递给对应的 thymeleaf html 文件进行显示。 ---
评论 5
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值