springboot访问template下的html页面,配置详情

Spring Boot项目默认不允许直接访问template下的文件,可配置视图解析器来访问。本文以thymeleaf为例,介绍了配置步骤,包括在pom.xml添加依赖、在application.yml中添加配置、在template下添加index.html文件、后台action配置映射关系,最后展示了访问结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、template下文件不允许直接访问

1、查资料得知:springboot项目默认是不允许直接访问template下的文件的,是受保护的。

     所以想访问template下的html页面,我们可以配置视图解析器。

2、如果想要用视图去展示,应该要设置好视图展示页面,比如说用一个模板语言来接收返回的数据(thymeleaf或者freemarker等), 也可以用jsp接收,但是SpringBoot官方是不推荐用jsp的,而是建议使用thymeleaf作为模板语言,这里我以thymeleaf为例。

二、配置步骤

1、pom.xml添加依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2、application.yml中添加配置

spring:
  thymeleaf:
    prefix:
      classpath: /templates   # 访问template下的html文件需要配置模板,映射
    cache: false # 开发时关闭缓存,不然没法看到实时页面

3、template下添加一个index.html文件

4、后台action配置映射关系

这里有两种方法,经过尝试都可以访问 index.html 页面

三、结果展示

1、访问index1,返回到index.html页面了

2、访问index2,访问到html页面了

只不过,我这里没有返回数据,所以列表没有数据,但是返回到页面了

Spring Boot 提供了内置的Thymeleaf或FreeMarker等模板引擎支持,用于动态生成HTML页面访问模板URL通常涉及到WebMvc配置视图解析器的设置。以下是基本步骤: 1. **添加依赖**:如果你选择使用Thymeleaf,需要在`pom.xml`文件中添加Thymeleaf的starter依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> ``` 对于FreeMarker,添加对应的starter: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> ``` 2. **配置视图Resolver**:在`application.properties`或`application.yml`中配置视图解析器的位置,例如: ```properties spring.freemarker.template-path=classpath:/templates/ spring.thymeleaf.cache=false spring.thymeleaf.mode=HTML5 ``` 这里的路径指定的是模板文件所在的目录。 3. **创建Controller**:创建一个Controller并使用`@GetMapping`映射一个URL到一个视图名称,如`/index.html`: ```java import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class HomeController { @GetMapping("/") public ModelAndView home() { // 假设返回的数据模型名为model ModelAndView modelAndView = new ModelAndView("home"); modelAndView.addObject("message", "Hello Spring Boot!"); return modelAndView; } } ``` 4. **访问URL**:现在你可以通过`http://your-app-url/index.html`访问这个模板页面,其中"your-app-url"替换为实际的应用运行地址。
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值