这里有新鲜出炉的精品教程, 程序狗速度看过来!
Spring Boot
Spring Boot 项目旨在简化创建产品级的 Spring 应用和服务你可通过它来选择不同的 Spring 平台可创建独立的 Java 应用和 web 应用, 同时提供了命令行工具来允许'spring scripts'.
这篇文章主要介绍了详解使用 Spring Boot 开发 Web 项目, 具有一定的参考价值, 感兴趣的小伙伴们可以参考一下
前面两篇博客中我们简单介绍了 spring Boot 项目的创建并且也带小伙伴们来 DIY 了一个 Spring Boot 自动配置功能, 那么这些东西说到底最终还是要回归到 Web 上才能体现出它的更大的价值, so, 今天我们就来看一下如何使用 Spring Boot 来开发 Web 项目当然, 如果小伙伴对 Spring Boot 尚不熟悉的话, 可以先参考一下这两篇博客:
1. 初识 Spring Boot 框架
2. 初识 Spring Boot 框架 (二) 之 DIY 一个 Spring Boot 的自动配置
Spring Boot 提供了 spring-boot-starter-web 来为 Web 开发予以支持, spring-boot-starter-web 为我们提供了嵌入的 Tomcat 以及 SpringMVC 的依赖, 用起来很方便另外, 我们这里还要用到模板引擎, 我们做 web 开发可选的模板引擎还是挺多的, 这里我主要使用 Thymeleaf 作为模板引擎, 事实上, Spring Boot 提供了大量的模板引擎, 包括 FreeMarkerGroovyThymeleafVelocity 和 Mustache, 在 提供的这么多中它推荐使用 ThymeleafThymeleaf 在使用的过程中通过 ThymeleafAutoConfiguration 类对集成所需要的 Bean 进行自动配置, 通过 ThymeleafProperties 来配置 Thymeleaf, 包括前缀后缀什么的, 我们可以查看 ThymeleafProperties 一段源码:
- @ConfigurationProperties("spring.thymeleaf")
- public class ThymeleafProperties {
- private static final Charset DEFAULT_ENCODING = Charset.forName("UTF-8");
- private static final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf("text/html");
- public static final String DEFAULT_PREFIX = "classpath:/templates/";
- public static final String DEFAULT_SUFFIX = ".html";
- private boolean checkTemplate = true;
- private boolean checkTemplateLocation = true;
- private String prefix = "classpath:/templates/";
- private String suffix = ".html";
- private String mode = "HTML5";
- ......
- ......
- ......
- }
OK, 从这一段源码中我们可以看到默认的页面后缀名为. html, 前缀为 classpath:/templates/, 实际上也就是我们需要把 html 页面放到 resources 文件夹下的 templates 文件夹中同时我们也看到了要如何修改这个配置, 在 application.properties 文件中以 spring.thymeleaf 为前缀来配置相关属性
创建 Project
注意创建的时候要选择 Thymeleaf 作为依赖, 这样创建成功的 Project 中将自动包含 spring-boot-starter-web, 如下图:
创建 JavaBean
我一会要从后台传递数据给前台页面, 数据的载体就是这个 JavaBean, 如下:
- public class Person {
- private String name;
- private Integer age;
- public Person() {
- super();
- }
- public Person(String name, Integer age) {
- super();
- this.name = name;
- this.age = age;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public Integer getAge() {
- return age;
- }
- public void setAge(Integer age) {
- this.age = age;
- }
- }
后台数据构造
在入口类中添加如下代码, 由后台向前台页面返回两条数据, 一个单个的 Person 对象, 还有一个 people 对象是一个 List 集合, 集合中放了 3 个 Person 对象, 到时候我们直接将这两条数据在 html 页面上显示出来, 代码如下:
- @RequestMapping("/")
- public String index(Model model) {
- Person single = new Person("aa", 11);
- List<Person> people = new ArrayList<>();
- Person p1 = new Person("zhangsan", 11);
- Person p2 = new Person("lisi", 22);
- Person p3 = new Person("wangwu", 33);
- people.add(p1);
- people.add(p2);
- people.add(p3);
- model.addAttribute("singlePerson", single);
- model.addAttribute("people", people);
- return "index";
- }
这里的代码都很简单, 不必我多说了, 就是返回给前台页面两个对象, 一个 singlePerson, 一个 people, 另外, 我们的前台页面叫做 index.html
引入相关的静态文件
这里我使用到了 Bootstrap 和 jQuery 两个库, 当然这个并不是必须的, 只是为了让我们显示的效果更好看一些, 静态文件我们要放在 src/main/resources/static 目录下
放置之后目录如下:
前台展示页面
刚才小伙伴们都看到了, 默认情况下前台页面要放在 src/main/resources/templates 目录下, so, 我们在该目录下新建文件就叫 index.html, 如下:
- <html lang="en" xmlns:th="http://www.thymeleaf.org">
- <head>
- <meta charset="UTF-8" />
- <title>Test20</title>
- <link th:href="@{bootstrap/CSS/bootstrap.min.css}" rel="external nofollow" rel="external nofollow" rel="stylesheet" />
- <link th:href="@{bootstrap/css/bootstrap-theme.min.css}" rel="external nofollow" rel="stylesheet" />
- </head>
- <body>
- <div class="panel panel-primary">
- <div class="panel-heading">
- <h3 class="panel-title">访问 Model</h3>
- </div>
- <div class="panel-body">
- <span th:text="${singlePerson.name}"></span>
- </div>
- </div>
- <div th:if="${not #lists.isEmpty(people)}">
- <div class="panel panel-primary">
- <div class="panel-heading">
- <h3 class="panel-title">列表</h3>
- </div>
- <div class="panel-body">
- <ul class="list-group">
- <li class="list-group-item" th:each="person:${people}">
- <span th:text="${person.name}"></span>
- <span th:text="${person.age}"></span>
- <button class="btn" th:onclick="'getName(\''+${person.name}+'\');'">获得名字</button>
- </li>
- </ul>
- </div>
- </div>
- </div>
- <script th:src="@{jquery-3.1.1.js}" type="text/javascript"></script>
- <script th:src="@{bootstrap/js/bootstrap.min.js}" type="text/javascript"></script>
- <script th:inline="javascript">
- var single = [[${singlePerson}]];
- console.log(single.name+"/"+single.age);
- function getName(name) {
- console.log(name);
- }
- </script>
- </body>
- </html>
关于这一段 html 文件我简单介绍一下, 首先通过 xmlns:th="http://www.thymeleaf.org" 导入命名空间, 在后期时候的时候, 由于 html 本身是静态视图, 在使用相关属性的时候加上 th: 前缀可以使之变为动态视图 th:href="@{bootstrap/css/bootstrap.min.css}" rel="external nofollow" rel="external nofollow" 表示引用 Web 静态资源 OK, 这是 head 部分 body 部分整体上分为了两大块, 第一块显示我那个单独的 Person 对象, 第二部分显示 List 集合中的 Person 对象 div 的样式这个没啥好说的, 照着 Bootstrap 的官网写就行了, th:text="${singlePerson.name}" 表示访问 model 中 singlePerson 的 name 属性, th:if="${not #lists.isEmpty(people)}" 表示判断 model 中的 people 集合是否为空, th:each="person:${people}" 表示遍历 people 中的元素, 这个和 Java 里的 foreach 差不多, person 表示迭代元素 th:onclick="'getName(\''+${person.name}+'\');'"表示添加点击事件, 点击事件由 JavaScript 来处理 th:inline="javascript" 这样添加到的 script 标签可以通过 [[${singlePerson}]] 访问 model 中的属性
如此之后, 我们便可以运行我们自己的项目了, 然后在浏览器中访问, 结果如下:
点击 Button 也可以在浏览器控制台看到 log 输出:
OK,perfect!
Tomcat 相关配置
上面几乎没做什么特别的配置, 大部分都使用了 SpringBoot 提供的默认的配置方式有的时候我们可能需要有一些自定义的配置, 比如 Tomcat 的配置, 很简单, 和上上篇博客说的基本一致, 有两种不同的配置方式:
在 application.properties 中配置
直接在 application.properties 中进行配置即可, 如下:
- server.port=8081# 配置服务器端口, 默认为 8080
- server.session-timeout=1000000# 用户回话 session 过期时间, 以秒为单位
- server.context-path=/index# 配置访问路径, 默认为 /
- server.tomcat.uri-encoding=UTF-8# 配置 Tomcat 编码, 默认为 UTF-8
- server.tomcat.compression=on#Tomcat 是否开启压缩, 默认为关闭
在代码中进行配置
- @Component
- public class CustomServletContainer implements EmbeddedServletContainerCustomizer {
- @Override
- public void customize(ConfigurableEmbeddedServletContainer container) {
- container.setPort(8080);
- container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND,"/404.html"));
- container.setSessionTimeout(10, TimeUnit.MINUTES);
- }
- }
自定义类实现
EmbeddedServletContainerCustomizer 接口, 然后设置端口设置错误请求页面设置会话超时时间等, 大家注意这里的 404 页面放在 src/main/resources/static 文件夹下, 有了这个之后, 当我访问一个不存在的页面的时候就会跳转到 404.html 页面了
SpringMVC 相关配置
虽然 Spring Boot 默认的配置很多情况都可以满足我们的项目需求, 可是有的时候我们可能还是会需要更加灵活的 SpringMVC 配置, 这个时候我们只需要自定义类继承自 WebMvcConfigurerAdapter, 然后使用 @Configuration 和 @EnableWebMvc 注解, 这样我们会完全屏蔽掉 Spring Boot 的默认配置, 但是正常情况下我们可能只是希望在 Spring Boot 已有默认配置的基础上再添加一些配置即 Spring Boot 提供的默认配置和我自定义的配置并存的情况, 这个也简单, 只需要去掉 @EnableWebMvc 注解就行了如下代码:
- @Configuration
- //@EnableWebMvc// 无需使用该注解, 否则会覆盖掉 SpringBoot 的默认配置值
- public class WebMVCConfig extends WebMvcConfigurerAdapter {
- @Override
- public void addViewControllers(ViewControllerRegistry registry) {
- registry.addViewController("/hello").setViewName("/hello");
- }
- }
自定义 Favicon
想要自定义 favicon 很简单, 只需要将自己的 favicon.ico 文件放置到 src/main/resources 目录下即可, 重新运行项目, 再看浏览器左上角图标就会变了如下:
本案例下载地址: 本案例 GitHub 地址
来源: http://www.phperz.com/article/18/0318/357621.html