springboot视图解析器配置
时间: 2025-05-21 20:37:58 浏览: 18
### 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 文件进行显示。
---
阅读全文
相关推荐


















