学习码匠社区-spring boot 使用bootstrap + thymeleaf 制作导航栏
spring boot 使用 bootstrap + thymeleaf 制作导航栏
添加 thymeleaf 依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
配置 application.properties,使得 spring boot 能够找到模板文件
thymeleaf= model= HTML5 encoding= UTF-8 cache= false prefix= classpath:templates/ suffix= .html
添加 bootstrap
wget https://github.com/twbs/bootstrap/releases/download/v3.3.7/bootstrap-3.3.7-dist.zip
解压到项目的 resources/static 下
创建模板文件 index.html
拷贝官网的默认导航条 https://v3.bootcss.com/components/#navbar-default,并修改
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>码匠社区</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <!-- 最新版本的 Bootstrap 核心 CSS 文件 --> <link rel="stylesheet" href="css/bootstrap.min.css" /> <!-- 可选的 Bootstrap 主题文件(一般不用引入) --> <link rel="stylesheet" href="css/bootstrap-theme.min.css" /> <!-- 最新的 Bootstrap 核心 JavaScript 文件 --> <script src="js/bootstrap.min.js"></script> </head> <body> <nav class="navbar navbar-default"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false" > <span class="sr-only">码匠社区</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">码匠社区</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1" > <form class="navbar-form navbar-left"> <div class="form-group"> <input type="text" class="form-control" placeholder="搜索" /> </div> <button type="submit" class="btn btn-default">搜索</button> </form> <ul class="nav navbar-nav navbar-right"> <li><a href="#">Link</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false" >我<span class="caret"></span ></a> <ul class="dropdown-menu"> <li><a href="#">消息中心</a></li> <li><a href="#">个人资料</a></li> <li><a href="#">退出登录k</a></li> </ul> </li> </ul> </div> <!-- /.navbar-collapse --> </div> <!-- /.container-fluid --> </nav> </body> </html>
编写 IndexController 控制器预览效果
package com.byrxiaochun.community.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class IndexController { @GetMapping("/") public String index(){ return "index"; } }
问题
如果不在 application.propertites 中配置 thymeleaf, 访问时可能报错