服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - springboot如何使用thymeleaf模板访问html页面

springboot如何使用thymeleaf模板访问html页面

2021-04-28 11:21Tomthy Java教程

springboot中推荐使用thymeleaf模板,使用html作为页面展示。那么如何通过Controller来访问来访问html页面呢?下面通过本文给大家详细介绍,感兴趣的朋友跟随脚本之家小编一起看看吧

引言

在传统的web开发中通常使用jsp页面,首先需要在pom文件中引入springmvc相关的包,然后写springmvc的配置文件(包括访问资源的路径解析),之后还需再web.xml中配置访问路由。这无疑太麻烦了,每次开发前都需要编写大量的配置文件。

html">springboot为此提供了高效便捷的解决方案,只需再pom.xml中添加web开发的依赖,便可进行web开发,省去了繁琐的配置步骤。

下面为web开发引入的依赖

?
1
2
3
4
<dependency>
  <groupid>org.springframework.boot</groupid>
  <artifactid>spring-boot-starter-web</artifactid>
</dependency>

正文

那么在springboot中如果需要使用页面该怎么做呢?springboot不推荐使用jsp,因为jsp在springboot中有诸多限制,具体限制这里就不展开说了,大家感兴趣可以去网上查阅。springboot中推荐使用thymeleaf模板,使用html作为页面展示。那么如何通过controller来访问来访问html页面呢?

1.在pom.xml文件中添加thymeleaf依赖

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<dependencies>
  <dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-web</artifactid>
  </dependency>
  <dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-test</artifactid>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-thymeleaf</artifactid>
  </dependency>
</dependencies>

2.在application.yml中添加访问请求配置

?
1
2
3
4
5
6
##thymeleaf页面模板配置
spring:
 mvc:
  view:
   prefix: /
   suffix: .html

springboot中默认resources中static文件夹存放静态资源,如js文件、css文件、图片等等。templates文件夹中存放html页面。

3.在templates文件夹中创建hello.html

?
1
2
3
4
5
6
7
8
9
10
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8"/>
  <title>title</title>
</head>
<body>
hello world
</body>
</html>

4.编写controller

?
1
2
3
4
5
6
7
8
9
10
/**
 * created by tomthy on 2018/5/10
 */
@controller
public class contentcontroller {
  @getmapping("/hello")
  private string helloworld(){
    return "hello";
  }
}

 

注意:不要使用@restcontroller注解,@restcontroller注解是@responsebody和@controller的集合体,使用@restcontroller注解会默认返回数据,而不会请求到页面。

5.在浏览器中输入请求地址

输入地址:http://localhost:8080/hello 便可请求到hello.html页面。

springboot如何使用thymeleaf模板访问html页面

6.静态资源的访问

html页面中使用到静态资源时(如图片),直接使用<script type="text/javascript" src="/js/wangeditor.js"></script>。js为static下的文件夹。

7.项目目录

springboot如何使用thymeleaf模板访问html页面

总结

以上所述是小编给大家介绍的springboot使用thymeleaf模板访问html页面,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!

原文链接:https://www.jianshu.com/p/bd7a821515ec

延伸 · 阅读

精彩推荐