Spring Boot第一个简单返回html页面的程序

1、首先,新增多一个class类,代码如下:

package com.springboot.test;

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

@Controller
public class OkApplication {

    @RequestMapping("/hehe")
    public String gg(){
        return "hello";
    }

}

注:这里gg()方法返回的hello字符串,后面我们新增一个html页面在templates底下要命名为hello.html,才可以显示出来,如果放在templates文件夹的test目录底下,就要返回test/hello

2、由于Spring Boot加载页面需要第三方库thymeleaf来加载,所以需要进行下面两个的配置

(1)、打开项目底下的application.properties配置文件,修改如下:

spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

(2)、由于使用了第三方库thymeleaf,因此需要在pom.xml加上这个库的相关依赖,加上下面这段代码即可:

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

(3)、再pom.xml文件底下右键菜单选择maven,Reimport,把thymeleaf依赖库加到项目底下,如下图所示:

3、接着,在resources目录底下的static增加一张图片mm.jpg,用于等下所需显示的html页面,在templates目录底下新增一个hello.html文件,目录结构,及相关代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>噢噢</title>
</head>
<body>
    <h1>你好呀,Spring Boot</h1>
    <img src="mm.jpg">
</body>
</html>

4、接着,运行项目,之后地址栏输入http://localhost:8080/hehe,如下图所示:

5、这样就可以显示一个html页面了,以上内容仅供参考学习,谢谢!

发布了276 篇原创文章 · 获赞 200 · 访问量 72万+

猜你喜欢

转载自blog.csdn.net/u012561176/article/details/91045487