素材牛VIP会员
SpringBoot + Thymeleaf 引入的css、js文件无效
 霸***解  分类:Html5  人气:1530  回帖:9  发布于6年前 收藏

今天尝试用spring boot + thymeleaf 集成 bootstrap 做一个简单的登录页面, 参考着官方教程做:登录页。

最开始的时候,我先用<link>标签导入bootstrap, 然后因为登录页自身的css样式不多,就用<style>做成内联样式放在了页面内部,当时的情况是内联样式起效但外部bootstrap.css没起作用。 后来把登录页的css设置放到独立样式表中后,整个页面就彻底不渲染了。

下面是官方教程的效果与我运行的结果:


css文件夹我已经放在了statis路径下,引入也是用的thymeleaf th:href="@{/css/bootstrap.css}"标准语法,实在想不通为什么会不起作用。

下面是工程结构:

index.html页面代码

<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">

    <link th:href="@{/css/bootstrap.css}" rel="stylesheet" type="text/css">
    <link th:href="@{/css/signin.css}" rel="stylesheet" type="text/css">
    <title>Index</title>

</head>

<body>

<div class="container">

    <form class="form-signin">
        <h2 class="form-signin-heading">Please sign in</h2>
        <label for="inputEmail" class="sr-only">Email address</label>
        <input type="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
        <label for="inputPassword" class="sr-only">Password</label>
        <input type="password" id="inputPassword" class="form-control" placeholder="Password" required>
        <div class="checkbox">
            <label>
                <input type="checkbox" value="remember-me"> Remember me
            </label>
        </div>
        <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
    </form>

</div>

<script th:src="@{/js/jquery-3.2.1.js}"></script>
<script th:src="@{/js/bootstrap.js}"></script>

</body>
</html>

application.properties设置

spring.thymeleaf.cache=false
spring.thymeleaf.mode=HTML5

Controller代码

package com.wxm.controller;

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

/**
 * @Author Created by OracleMing from IMSE of BUAA.
 * @Time 2017-07-07-20:24.
 * @Description 索引页面路由控制器
 */
@Controller
public class IndexController {

    @RequestMapping(name = "/index")
    public String indexPage(){
        return "index";
    }

}

讨论这个帖子(9)垃圾回帖将一律封号处理……

Lv6 码匠
co***ky Linux系统工程师 6年前#1

SpringBoot全服务化(Rest),然后页面用NG、React、VUE等。

Lv6 码匠
qx***23 Linux系统工程师 6年前#2

还是没有样式哎

Lv4 码徒
go***le 学生 6年前#3
<link rel="stylesheet" type="text/css" href="/css/app.css">

复制,然后把css文件名改一下,就可以了。
我就是这么解决的。

Lv1 新人
凌***志 移动开发工程师 6年前#4

打开浏览器的开发者工具,切换到network看下请求的链接吧。

不建议用th:href="@{/css/bootstrap.css}这样的写法,推荐使用绝对路径:

th:href="@{~/css/bootstrap.css}

Lv5 码农
风***在 产品经理 6年前#5

直接引入吧,或者你看看控制台有没有错误。

Lv5 码农
wg***ge 页面重构设计 6年前#6

您好,我遇到了跟您相同的问题,请问您现在解决了吗,我用的模板也跟您一样,我也正被这个问题困扰着

Lv1 新人
真***溜 职业无 6年前#7

兄弟 别用模板 追求动静分离才是正解

Lv4 码徒
pe***ei 移动开发工程师 6年前#8

不用模板引入,直接正常引入试试

Lv7 码师
亡***师 JS工程师 6年前#9

和你遇到同样的问题,我觉得是目前thymeleaf的LEGACYHTML5的写法不够完善,目前没有解决

 文明上网,理性发言!   😉 阿里云幸运券,戳我领取