springboot调用HTML文件注意事项及说明

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

springboot调用HTML文件注意事项及说明

不知名的曹同学   2022-11-19 我要评论

springboot调用HTML文件注意事项

1.配置thymeleaf

2.HTML代码头部需要添加以下代码

<link rel="stylesheet" type="text/css" href="/static/css/style.css" rel="external nofollow"  th:href="@{css/style.css}" rel="external nofollow" />

其中th为

<html lang="en" xmlns:th="http://www.thymeleaf.org">

3.关于controller和requestmapping

@Controller
//只能使用controller,如果使用RestController将只会返回字符串不会返回html页面
@RequestMapping("/login")  //此处的request。。。是下面整个模块的地址,如果想要访问下面的方法
需要在下面的方法上面单独请求
public class LoginController {
    @RequestMapping("")  //需要在此处单独请求
    public String login(){
        return "/login";
    }
}

springboot项目访问HTML页面

引入相关依赖

<!--支持跳转,springboot推荐使用thymeleaf模板引擎-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    <!--指定themleaft版本-->
    <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
    <thymeleaf-layout-dialect.version>2.0.5</thymeleaf-layout-dialect.version>
</properties>

增加springboot配置项

#thymeleaf模版前缀
spring.thymeleaf.prefix=classpath:/templates/

在 src/main/resources 目录下新建 static 目录和 templates 目录。 static存放静态文件,templates 存放静态页面(thymeleaf 模版)

在控制器中写明跳转模版方法

Handler访问映射地址跳转模版成功

总结这次遇到的问题

1. Error resolving template template might not exist or might not be accessible

控制器方法返回的模版名称没有前缀/,可手动添加/或添加springboot配置项

2. org.xml.sax.SAXParseException: 元素类型 “link” 必须由匹配的结束标记 “” 终止,org.xml.sax.SAXParseException: 元素类型 “meta” 必须由匹配的结束标记 “” 终止

开发工具生成的html页面元素有的没有终止符/,thymeleaf模板引擎默认是Template modes:HTML5解析的,解析比较严格。

需要手动添加/或指定引入的thymeleaf版本号

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们