SpringBoot学习02--SpringBoot访问HTML页面

 

本篇博客在SpringBoot学习01--Hello world程序的基础上进行,实现SpringBoot访问HTML页面功能。

 

操作前先了解:

SpringBoot的Web相关文件存放在src/main/resources目录下。

一般情况下static目录用于存放静态文件,例如css、图片等文件,templates用于存放HTML文件,

如果resources目录下没有这两个目录,需要自行新建出来。

 

步骤:

1.添加依赖

修改pom.xml文件,在</dependencies>的前一行添加thymeleaf模板引擎依赖

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

修改后IDEA右下角提示Maven projects need to be imported,选择Enable Auto-Import自动下载更新的依赖。

2.配置aplication.yml

重命名application.properties为application.yml(这样改之后可以让配置更加简洁)

修改aplication.yml为如下内容:

spring:
  thymeleaf:
    prefix: classpath:/templates/

3.编写HTML文件

在src/main/resources/templates目录下新建一个html文件

输入文件名 index-->OK

编写index.html内容

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>springboot web</title>
</head>
<body>
<h1>Hello Spring Boot!!!</h1>
<p th:text="${hello}"></p>
<div>
    <p th:text="${say}"></p>
</div>
</body>
</html>

 

4.编写控制类

新建一个存放控制类的controller包

新建控制类HTMLController.java

编辑HTMLController.java内容如下:

package com.jipson.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.HashMap;

@Controller
public class HTMLController {
    @RequestMapping("/hello")
    public String helloHtml(HashMap<String, Object> map, Model model) {
        model.addAttribute("say","欢迎欢迎,热烈欢迎");
        map.put("hello", "欢迎进入HTML页面");
        return "index";
    }
}

5.启动项目

右键DemoApplication类-->Run 'DemoApplication'

6.浏览器验证

浏览器输入localhost:8080/hello,看到如下界面为成功:

 

完整工程代码:

完整代码下载   提取码:fdls

 

 

参考:https://www.jianshu.com/p/198497e08e00

 

 

完成! enjoy it!

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值