欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

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

时间:2021-04-26 11:05:04|栏目:JAVA代码|点击:

引言

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

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

下面为web开发引入的依赖

<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依赖

  <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中添加访问请求配置

##thymeleaf页面模板配置
spring:
 mvc:
  view:
   prefix: /
   suffix: .html

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

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

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8"/>
  <title>Title</title>
</head>
<body>
hello world
</body>
</html>

4.编写Controller

/**
 * 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页面。

6.静态资源的访问

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

7.项目目录

总结

上一篇:java实现后台图片跨域上传功能

栏    目:JAVA代码

下一篇:java中Servlet Cookie取不到值原因解决办法

本文标题:springboot如何使用thymeleaf模板访问html页面

本文地址:http://www.codeinn.net/misctech/109235.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有