1.1、什么是springboot
上面是引自官网的一段话,大概是说: Spring Boot 是所有基于 Spring 开发的项目的起点。Spring Boot 的设计是为了让你尽可能快的跑起来 Spring 应用程序并且尽可能减少你的配置文件
简单的来说,使用springboot并不是什么新的框架,它默认配置了很多框架的使用方式,
它使用 “习惯优于配置” (项目中存在大量的配置,此外还内置一个习惯性的配置,让你无须)的理念让你的项目快速运行起来。
它并不是什么新的框架,而是默认配置了很多框架的使用方式,就像 Maven 整合了所有的 jar 包一样,Spring Boot 整合了所有框架。
1.2、使用SpringBoot的好处
1.快速构建项目
2.对主流开发框架的无配置集成
3.项目可独立运行,无需外部依赖Servlet容器,springboot中内嵌一个tomcat
4.提高开发效率,部署效率
5.与云计算的天然集成
例如:
其实就是简单、快速、方便!平时如果我们需要搭建一个spring web项目的时候需要怎么做呢?
1)配置web.xml,加载spring和spring mvc
2)配置数据库连接、配置spring事务
3)配置加载配置文件的读取,开启注解
4)配置日志文件
...
配置完成之后部署tomcat 调试
...
现在非常流行微服务,如果我这个项目仅仅只是需要发送一个邮件,如果我的项目仅仅是生产一个积分;我都需要这样折腾一遍!
但是如果使用spring boot呢?
很简单,我仅仅只需要非常少的几个配置就可以迅速方便的搭建起来一套web项目或者是构建一个微服务!
使用sping boot到底有多爽,用下面这幅图来表达
2.1、创建maven项目,pom文件
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.3.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.zhiyou100</groupId> <artifactId>springboot_test</artifactId> <version>0.0.1-SNAPSHOT</version> <name>springboot_test</name> <description>Demo project for Spring Boot</description>
<properties> <java.version>1.8</java.version> </properties>
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <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> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> |
2.2、编写helloworld服务
package com.zhiyou100.springboot_test;
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication @RestController public class SpringbootTestApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootTestApplication.class, args); } @RequestMapping("hello") public String index(){ return "helloworld"; } } |
2.3、部署运行
直接运行main方法即可
3.1、接收单个参数
@RequestMapping("getValue.do") @ResponseBody public String getAloneValue(Integer id){ return "a==>"+id; } |
3.2、接收对象
@RequestMapping("getUser.do") @ResponseBody public User getUser(User user){ return user; } |
4.1、请求转发到action
@RequestMapping("hello.do") public String hello(){ return "forward:hello2.do"; }
@RequestMapping("hello2.do") @ResponseBody public String hello2(){ return "hello2hahah"; } |
4.2、重定向到action
@RequestMapping("hello.do") public String hello(){ return "redirect:hello2.do"; }
@RequestMapping("hello2.do") @ResponseBody public String hello2(){ return "hello2hahah"; } |
4.3、请求转发到页面
@RequestMapping("toUI.do") public ModelAndView toUI(){
return new ModelAndView("hello.html"); } |
注意:在resource下的static目录中创建该html
添加依赖:
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> <version>2.1.3.RELEASE</version> </dependency> |
如果添加以上约束我们的页面需要在templates下
我们在开发web项目时,需要引入大量的js,css,图片等静态资源,SpringBoot默认将静态资源存放在classpath下,目录名须符合如下规则:
/static
/public
/resources
/META-INF/resources
例子:我们在项目的src/main/resources下创建static文件夹放一张图片,在地址栏中输入http://localhost:8080/图片名,如果在浏览器上显示图片则代表配置成功
在上边的案例中我们使用通过@ResponseBody注解向页面返回Json数据,name如果我们需要渲染html页面该怎么做呢?
5.1、模板引擎
SpringBoot为我们提供了多种模板引擎的默认配置支持,所以推荐使用模板引擎开发动态web项目。SpringBoot建议我们使用这些模板引擎,便面使用jsp,因为jsp无法实现SpringBoot的多种特性
SpringBoot提供了默认配置的模板引擎主要有:Thymeleaf,FreeMarker,Velocity,Groovy,Mustache
5.2、Thymeleaf
使用Thymeleaf需要引入pom配置并在src/main/resources/templates目录下创建html文件
5.2.1、显示单个数据
1)controller
@RequestMapping("host.do") public String test1(ModelMap map){ map.addAttribute("host","springboot-tlf"); return "index"; } |
- Html
注意:在html文件中引入xmlns:th="http://www.thymeleaf.org"命名空间可避免编辑器验证html出错,而且有代码提示
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1 th:text="${host}">Hello</h1> </body> </html> |
6.2.2、th属性解读
html有的属性,Thymeleaf基本都有,而常用的属性大概有七八个。其中th属性执行的优先级从1~8,数字越低优先级越高。
一、th:text :设置当前元素的文本内容,相同功能的还有th:utext,两者的区别在于前者不会转义html标签,后者会。优先级不高:order=7
二、th:value:设置当前元素的value值,类似修改指定属性的还有th:src,th:href。优先级不高:order=6
三、th:each:遍历循环元素,和th:text或th:value一起使用。注意该属性修饰的标签位置,详细往后看。优先级很高:order=2
四、th:if:条件判断,类似的还有th:unless,th:switch,th:case。优先级较高:order=3
五、th:insert:代码块引入,类似的还有th:replace,th:include,三者的区别较大,若使用不恰当会破坏html结构,常用于公共代码块提取的场景。优先级最高:order=1
六、th:fragment:定义代码块,方便被th:insert引用。优先级最低:order=8
七、th:object:声明变量,一般和*{}一起配合使用,达到偷懒的效果。优先级一般:order=4
- th:attr:修改任意属性,实际开发中用的较少,因为有丰富的其他th属性帮忙,类似的还有th:attrappend,th:attrprepend。优先级一般:order=5
使用Thymeleaf属性需要注意点以下五点:
一、若要使用Thymeleaf语法,首先要声明名称空间: xmlns:th="http://www.thymeleaf.org"
二、设置文本内容 th:text,设置input的值 th:value,循环输出 th:each,条件判断 th:if,插入代码块 th:insert,定义代码块 th:fragment,声明变量 th:object
三、th:each 的用法需要格外注意,打个比方:如果你要循环一个div中的p标签,则th:each属性必须放在p标签上。若你将th:each属性放在div上,则循环的是将整个div。参考jstl的循环
四、变量表达式中提供了很多的内置方法,该内置方法是用#开头,请不要与#{}消息表达式弄混。
- th:insert,th:replace,th:include 三种插入代码块的效果相似,但区别很大。
6.2.3、使用
页面
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Thymeleaf语法</title> </head> <body> <h2>Thymeleaf语法</h2> <!--th:text 设置原元素内容 常用--> <p th:text="${thText}"></p> <p th:utext="${thUText}"></p> <!--th:value 设置标签value属性值,常用--> <input th:value="${thValue}"></input> <!--th:each 遍历 常用--> <!--遍历div--> <!--<div th:each="message:${thEach}"> <p th:text="${thEach}"></p> </div>--> <!--只遍历p标签--> <div> <p th:text="${thEach}" th:each="messsage:${thEach}"></p> </div> <!--th:if 条件判断 类似的有th:switch.th:case,其中#strings是变量表达式的内置方法--> <p th:text="${thIf}" th:if="${not #strings.isEmpty(thIf)}"></p> </body> </html> |
Controller
package com.zhiyou100.controller;
import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping;
import java.util.ArrayList; import java.util.Arrays;
@Controller public class ThymelealfController {
@RequestMapping("host.do") public String test1(ModelMap map){ map.put("thText","<b>thText</b>"); map.put("thUText","<b>thUText</b>"); map.put("thValue","设置当前标签的value值"); map.put("thEach", Arrays.asList("th:each","遍历集合")); //map.put("thIf","IS NOT ENPTY"); return "index"; } } |
6.3、标准变量表达式
分类:
${...} 变量表达式,Variable Expressions
@{...} 链接表达式,Link URL Expressions
#{...} 消息表达式,Message Expressions
~{...} 代码块表达式,Fragment Expressions
*{...} 选择变量表达式,Selection Variable Expressions
6.3.1、代码块表达式
支持两种语法结构
推荐:~{templatename::fragmentname}
支持:~{templatename::#id}
templatename:模版名,Thymeleaf会根据模版名解析完整路径:/resources/templates/templatename.html,要注意文件的路径。
fragmentname:片段名,Thymeleaf通过th:fragment声明定义代码块,即:th:fragment="fragmentname"
id:HTML的id选择器,使用时要在前面加上#号,不支持class选择器。
代码块表达式的使用
代码块表达式需要配合th属性(th:insert,th:replace,th:include)一起使用。
th:insert:将代码块片段整个插入到使用了th:insert的HTML标签中,
th:replace:将代码块片段整个替换使用了th:replace的HTML标签中,
th:include:将代码块片段包含的内容插入到使用了th:include的HTML标签中,
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <!--th:fragment定义代码块标识--> <footer th:fragment="copy"> © 2012 The Good Thymes Virtual Grocery </footer>
<!--三种不同的引入方式--> <!--<div th:insert="tlf :: copy"></div>--> <!--<div th:replace="tlf :: copy"></div>--> <div th:include="tlf :: copy"></div>
<!--th:insert是在div中插入代码块,即多了一层div--> <div> <footer> © 2011 The Good Thymes Virtual Grocery </footer> </div> <!--th:replace是将代码块代替当前div,其html结构和之前一致--> <footer> © 2011 The Good Thymes Virtual Grocery </footer> <!--th:include是将代码块footer的内容插入到div中,即少了一层footer--> <div> © 2011 The Good Thymes Virtual Grocery </div> </body> </html> |
6.3.2、消息表达式
一般使用在国际化场景,结构:th:text=”#{msg}”
6.3.3、链接表达式
链接表达式好处
不管是静态资源的引用,form表单的请求,凡是链接都可以用@{...} 。这样可以动态获取项目路径,即便项目名变了,依然可以正常访问
链接表达式结构
无参:@{/xxx}
有参:@{/xxx(k1=v1,k2=v2)} 对应url结构:xxx?k1=v1&k2=v2
引入本地资源:@{/项目本地的资源路径}
引入外部资源:@{/webjars/资源在jar包中的路径}
例子
<link th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet"> <link th:href="@{/main/css/itdragon.css}" rel="stylesheet"> <form class="form-login" th:action="@{/user/login}" th:method="post" > <a class="btn btn-sm" th:href="@{/login.html(l='zh_CN')}">中文</a> <a class="btn btn-sm" th:href="@{/login.html(l='en_US')}">English</a> |
6.3.4、变量表达式
变量表达式有丰富的内置方法,功能强大,更方便
变量表达式功能
一、可以获取对象的属性和方法
二、可以使用ctx,vars,locale,request,response,session,servletContext内置对象
三、可以使用dates,numbers,strings,objects,arrays,lists,sets,maps等内置方法(重点介绍)
常用的内置对象
一、ctx :上下文对象。
二、vars :上下文变量。
三、locale:上下文的语言环境。
四、request:(仅在web上下文)的 HttpServletRequest 对象。
五、response:(仅在web上下文)的 HttpServletResponse 对象。
六、session:(仅在web上下文)的 HttpSession 对象。
七、servletContext:(仅在web上下文)的 ServletContext 对象
这里以常用的Session举例,用户刊登成功后,会把用户信息放在Session中,Thymeleaf通过内置对象将值从session中获取
// java 代码将用户名放在session中 session.setAttribute("userinfo",username); // Thymeleaf通过内置对象直接获取 th:text="${session.userinfo}" |
常用的内置方法
- strings:字符串格式化方法,常用的Java方法它都有。比如:equals,equalsIgnoreCase,length,trim,toUpperCase,toLowerCase,indexOf,substring,replace,startsWith,endsWith,contains,containsIgnoreCase等
- numbers:数值格式化方法,常用的方法有:formatDecimal等
- bools:布尔方法,常用的方法有:isTrue,isFalse等
- arrays:数组方法,常用的方法有:toArray,length,isEmpty,contains,containsAll等
- lists,sets:集合方法,常用的方法有:toList,size,isEmpty,contains,containsAll,sort等
- maps:对象方法,常用的方法有:size,isEmpty,containsKey,containsValue等
七、dates:日期方法,常用的方法有:format,year,month,hour,createNow等
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h2>ITDragon Thymeleaf 内置方法</h2> <h3>#strings </h3> <div th:if="${not #strings.isEmpty(itdragonStr)}" > <p>Old Str : <span th:text="${itdragonStr}"/></p> <p>toUpperCase : <span th:text="${#strings.toUpperCase(itdragonStr)}"/></p> <p>toLowerCase : <span th:text="${#strings.toLowerCase(itdragonStr)}"/></p> <p>equals : <span th:text="${#strings.equals(itdragonStr, 'itdragonblog')}"/></p> <p>equalsIgnoreCase : <span th:text="${#strings.equalsIgnoreCase(itdragonStr, 'itdragonblog')}"/></p> <p>indexOf : <span th:text="${#strings.indexOf(itdragonStr, 'r')}"/></p> <p>substring : <span th:text="${#strings.substring(itdragonStr, 2, 8)}"/></p> <p>replace : <span th:text="${#strings.replace(itdragonStr, 'it', 'IT')}"/></p> <p>startsWith : <span th:text="${#strings.startsWith(itdragonStr, 'it')}"/></p> <p>contains : <span th:text="${#strings.contains(itdragonStr, 'IT')}"/></p> </div>
<h3>#numbers </h3> <div> <p>formatDecimal 整数部分随意,小数点后保留两位,四舍五入: <span th:text="${#numbers.formatDecimal(itdragonNum, 0, 2)}"/></p> <p>formatDecimal 整数部分保留五位数,小数点后保留两位,四舍五入: <span th:text="${#numbers.formatDecimal(itdragonNum, 5, 2)}"/></p> </div>
<h3>#bools </h3> <div th:if="${#bools.isTrue(itdragonBool)}"> <p th:text="${itdragonBool}"></p> </div>
<h3>#arrays </h3> <div th:if="${not #arrays.isEmpty(itdragonArray)}"> <p>length : <span th:text="${#arrays.length(itdragonArray)}"/></p> <p>contains : <span th:text="${#arrays.contains(itdragonArray, 5)}"/></p> <p>containsAll : <span th:text="${#arrays.containsAll(itdragonArray, itdragonArray)}"/></p> </div> <h3>#lists </h3> <div th:if="${not #lists.isEmpty(itdragonList)}"> <p>size : <span th:text="${#lists.size(itdragonList)}"/></p> <p>contains : <span th:text="${#lists.contains(itdragonList, 0)}"/></p> <p>sort : <span th:text="${#lists.sort(itdragonList)}"/></p> </div> <h3>#maps </h3> <div th:if="${not #maps.isEmpty(itdragonMap)}"> <p>size : <span th:text="${#maps.size(itdragonMap)}"/></p> <p>containsKey : <span th:text="${#maps.containsKey(itdragonMap, 'thName')}"/></p> <p>containsValue : <span th:text="${#maps.containsValue(itdragonMap, '#maps')}"/></p> </div> <h3>#dates </h3> <div> <p>format : <span th:text="${#dates.format(itdragonDate)}"/></p> <p>custom format : <span th:text="${#dates.format(itdragonDate, 'yyyy-MM-dd HH:mm:ss')}"/></p> <p>day : <span th:text="${#dates.day(itdragonDate)}"/></p> <p>month : <span th:text="${#dates.month(itdragonDate)}"/></p> <p>monthName : <span th:text="${#dates.monthName(itdragonDate)}"/></p> <p>year : <span th:text="${#dates.year(itdragonDate)}"/></p> <p>dayOfWeekName : <span th:text="${#dates.dayOfWeekName(itdragonDate)}"/></p> <p>hour : <span th:text="${#dates.hour(itdragonDate)}"/></p> <p>minute : <span th:text="${#dates.minute(itdragonDate)}"/></p> <p>second : <span th:text="${#dates.second(itdragonDate)}"/></p> <p>createNow : <span th:text="${#dates.createNow()}"/></p> </div> </body> </html> |
Controller
public String test1(ModelMap map){ map.put("itdragonStr", "itdragonBlog"); map.put("itdragonBool", true); map.put("itdragonArray", new Integer[]{1,2,3,4}); map.put("itdragonList", Arrays.asList(1,3,2,4,0)); Map itdragonMap = new HashMap(); itdragonMap.put("thName", "${#...}"); itdragonMap.put("desc", "变量表达式内置方法"); map.put("itdragonMap", itdragonMap); map.put("itdragonDate", new Date()); map.put("itdragonNum", 888.888D); return "tlf2"; } |
8.4、应用
使用Thymeleaf完成查询和提交数据
Controller
package com.zhiyou100.controller;
import com.zhiyou100.pojo.Goods; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import java.util.ArrayList;
@Controller public class GoodsController {
//查询 @RequestMapping("show.do") public String queryAll(ModelMap map){ ArrayList<Goods> goods = new ArrayList<>(); goods.add(new Goods(1,"小米6","2299")); goods.add(new Goods(1,"小米8","2999")); goods.add(new Goods(1,"小米8探索版","3299")); goods.add(new Goods(1,"小米9","2999")); goods.add(new Goods(1,"小米9尊享版","3999")); map.addAttribute("goods",goods); return "show"; } @RequestMapping("delete.do") public String delete(Integer goods_id){ System.out.println(goods_id); return "show"; } } |
页面
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>显示页面</title> </head> <body>
<table> <tr> <td>商品编号</td> <td>商品名称</td> <td>商品价格</td> <td>相关操作</td> </tr> <tr th:each="good:${goods}"> <td th:text="${good.goods_id}"></td> <td th:text="${good.goods_name}"></td> <td th:text="${good.goods_price}"></td> <td><a th:href="@{delete.do(goods_id=${good.goods_id})}" th:text="删除"></a></td> </tr> </table>
</body> </html> |
具体更多操作请参考官网:https://www.thymeleaf.org
7.0、配置pom文件
在pom文件中引入mybatis依赖和mysql数据库依赖
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.2.0</version> </dependency> |
7.1、创建数据表
略
7.2、创建实体类
略
7.3、创建实体类映射文件
略,在resource目录下创建mapper目录创建映射文件
7.4、创建mapper
package com.zhiyou100.mapper; import com.zhiyou100.pojo.Goods; import org.apache.ibatis.annotations.Mapper; import java.util.List;
@Mapper public interface IGoodsMapper { List<Goods> queryAll(); } |
7.5、创建service
调用mapper,略
7.6、创建Controller
略
7.7、配置数据库连接
在application.properties文件中配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/springboot?serverTimezone=GMT%2B8 spring.datasource.username=root spring.datasource.password=123456 #读取实体类映射文件 mybatis.mapper-locations=classpath:mapper/*.xml |
8.1、SpringBoot实现原理
SpringBoot是由自动配置和启动器以及大量注解实现。
8.2、什么是自动配置
因为SpringBoot提供了配置应用程序和框架所需的基本配置,这就是自动配置。其实SpringBoot就是一个框架库,默认配置很多其他的主流框架可以快速使用。
8.2、Spring Boot Stater
启动器是一套方便的依赖描述符,他可以放在自己的程序中,只需要导入相关的pom约束不需要写代码或者配置就可以使用spring和其他的技术
比如:
spring-boot-starter-web
spring-boot-starter-jdbc
spring-boot-starter-thymeleaf