1.springBoot介绍
2.springboot的特性
3.springBoot之helloWorld
4.springBoot返回JSON数据
5.Spring Boot使用第三方json插件-fastJson
6.springBoot热部署(devtools)
7.spring Boot JPA/Hibernate/Spring Data 概念
8.springBoot JPA实现持久化操作
9.spring Data JPA实现持久化操作 详解
10.springBoot jdbcTemplate
12.springBoot之helloWorld访问404
13.配置server信息
14.springBoot中使用thymeleaf(模板引擎)
1.springBoot介绍
Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,Spring Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者。
2.springboot的特性
- 创建独立的Spring应用程序
- 嵌入的Tomcat,无需部署WAR文件
- 简化Maven配置
- 自动配置Spring
- 提供生产就绪型功能,如指标,健康检查和外部配置
- 绝对没有代码生成并且对XML也没有配置要求
说明:
它为spring的开发提供更快的入门体验,没有代码生成,没有配置文件,同时也可以修改默认值来满足特定的需求。
提供了一些大型项目中常见的非功能特性,比如嵌入式服务器,程序安全,健康监控等…
它不是对spring功能上的增强,而是提供了一种快速使用spring的方式
3.springBoot之helloWorld
(1)创建maven项目,添加pom.xml文件
a.添加parent依赖,引入这个之后,相关的引入就不需要添加version的配置,springboot会自动选择最合适的版本进行添加
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.5.RELEASE</version>
<relativePath/>
</parent>
b.添加jar包依赖
<dependencies>
<!-- mvc,aop的依赖包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!-- 由于我们在上面指定了parent,这里就不需要指定版本号 -->
</dependency>
</dependencies>
c.jdk,编码描述:
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.7</java.version>
</properties>
(2)在src/main/java下新建控制器类
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController//等价于@Controller和@ResponseBody
public class HelloController {
/**
* 请求地址映射,请求地址:http://localhost:8080/hello
* 这里的hello是请求名,不是项目名
* @return
*/
@RequestMapping("/hello")
public String hello(){
return "helloWord";//这里返回的字符串直接变成页面显示的信息
}
}
(3)启动测试:
a.使用注解启动
//这里的@SpringApplication指定这是一个springBoot程序
@SpringBootApplication
public class Test1 {
public static void main(String[] args) {
SpringApplication.run(Test1.class,args);
}
}
注意:
jdk版本问题,controller类以及被扫描的包要和测试文件在同包或其子包中,不然程序无法自动扫描@RequestMapping
访问地址:http://localhost:8080/请求名
在controller 的方法中 地址映射加入指定编码格式 这个时候也中文不乱码了
@RequestMapping(value = “/”, produces = “application/json; charset=utf-8”)
或者:
spring.http.encoding.force=true
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
server.tomcat.uri-encoding=UTF-8
4.springBoot返回JSON数据
springboot默认使用的json解析框架是jackson,相比较于springMVC来说,这里不需要再添加
@ResponseBody来标记返回json格式
示例代码:
public class Users {
private int id;
private String name;
private int age;
生成get/set方法
}
处理方法:
@RequestMapping("/hello")
public Users hello(){
Users user=new Users();
user.setId(11);
user.setName("张三");
user.setAge(18);
return user;
}
页面返回值:
{“id”:11,“name”:“张三”,“age”:18}
缺点:日期没有转换
5.Spring Boot使用第三方json插件-fastJson
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.15</version>
</dependency>
注意:要求版本在1.2.10以上
配置fastjson的方式一:
(1)启动类继承WebMvcConfigurerAdapter
(2) 覆盖方法:configureMessageConverters
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
System.out.println(“aaaa”);
//1.创建一个convert转换消息的对象
FastJsonHttpMessageConverter fastconverter=
new FastJsonHttpMessageConverter();
//2.添加fastJson的配置信息,例如:是否需要格式化返回的json数据
FastJsonConfig jsonConfig=new FastJsonConfig();
jsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
//3.在convert中添加配置信息
fastconverter.setFastJsonConfig(jsonConfig);
//4.将convert添加到converters当中
converters.add(fastconverter);
}
测试:在实体类中添加属性,并使用注解@JsonField
@JSONField(format = “yyyy-MM-dd”)
private Date date;
配置方式2:
在启动类中,注入bean:HttpMessageConverters
@Bean
public HttpMessageConverters abc(){
FastJsonHttpMessageConverter messageConverter=
new FastJsonHttpMessageConverter();
FastJsonConfig jsonConfig=new FastJsonConfig();
jsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
messageConverter.setFastJsonConfig(jsonConfig);
HttpMessageConverter converter=messageConverter;
return new HttpMessageConverters(converter);
}
测试:在实体类中添加属性,并使用注解@JsonField
@JSONField(format = “yyyy-MM-dd”)
private Date date;
结果:
优点:可以使用@JSONField注解
@JSONField(format="") 格式化时间
@JSONField(serialize = false)不序列化属性
6.springBoot热部署(devtools)
(1)热部署指的是修改代码后不需要重新启动服务器
spring-Boot-devtools 是一个为开发者服务的一个模块,其中最重要的功能就是自动应用
代码更改到最新的app上面去,原理是在发现代码更改之后,重新启动应用,但是速度比手动停止再 启动更快。
其深层原理,是使用了两个ClassLoader,一个ClassLoader加载那些不会变的类(第三方jar包),另一个Classloader加载会更改的类,称为restart ClassLoader
这样在有代码更改的时候,原来的restart Classloader被丢弃,重新创建一个restart
ClassLoader,由于需要加载的类相比较少,所以实现了较快的重启时间(5秒内)
(2)实现方式:修改pom.xml文件
添加依赖包:
<dependency>
<!--Spring 官方提供的热部署插件 -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<version>1.4.3.RELEASE</version>
</dependency>
(3)修改idea配置:
1、Settings --> 查找build project automatically --> 选中
2、CTRL + SHIFT + A --> 查找Registry --> 找到并勾选compiler.automake.allow.when.app.running
最后重启idea
说明:devtools在你保存程序后,自动重启服务器
补充:eclipse中添加热部署插件:
使用方法 注意:先把之前的springloader注释掉(pom.xml和vm arguments的值) a.添加依赖包
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <version>1.5.2.RELEASE</version> <optional>true</optional> <scope>true</scope> </dependency> b.添加plugin <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <!-- fork:如果没有设置该项,devtools不会起作用,即应用不会restart --> <fork>true</fork> </configuration> </plugin> </plugins> </build>
不能使用可能的原因:
a.对应的spring-boot版本是否正确
b.是否加入plugin以及属性true
c.eclipse project 是否开启了Build Automatically(自动编译)
d.如果设置SpringApplication.setRegisterShutdownHook(false),则自动重启将不起作用
7.spring Boot JPA/Hibernate/Spring Data 概念
(1)什么是JPA?
JPA全称JAVA Persistence API,JPA通过JDK5.0注解或xml描述对象-关系表的映射
关系,并将运行期的实体对象持久化到出具库中
(2)什么是springData
是一个用于简化数据库访问,并支持云服务的开源框架,主要目标是使得数据库的访问变得方便快捷,并支持map-reduce框架和云计算数据服务。此外还支持基于关系型数据库的数据服务。spring data会让数据的访问变得更加方便
(3)什么是spring Data JPA
可以极大地简化JPA的写法,可以在几乎不用写实现的情况下,实现对数据的访问和操作。
除了CRUD外,还包括如分页,排序等和功能。Spring Data是一个开源框架,Spring Data
JPA是这个框架中的一个模块,spring Data JPA的出现就是为了简化JPA的写法,让你只需要编写一个接口继承一个类就能实现CRUD操作了
(4)JPA/hibernate的关系
JPA是一种规范,而hibernate是它的一种实现。使用JPA的一个好处是,可以更换实现而不必改动太多代码
8.springBoot JPA实现持久化操作
(1)实现步骤:
a.需要添加相应的依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>1.5.2.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.41</version>
</dependency>
b.需要在application.properties(resources文件夹)文件添加配置信息
##链接数据库信息
spring.datasource.url=jdbc:mysql://localhost:3306/bcd
spring.datasource.username=root
spring.datasource.password=12345
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.max-active=20
spring.datasource.max-idle=8
spring.datasource.min-idle=8
spring.datasource.initial-size=10
### spring jpa配置信息
spring.jpa.database=MYSQL
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming- strateg=org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
c.需要创建一个实体类,比如:Cat
@Entity
public class Cat {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String catName;
//get/set方法
}
d.需要创建一个接口集成CrudRepository
//这是一个接口,不是class
public interface CatRepository extends CrudRepository<Cat,Integer> {}
e.需要创建一个Service
public class CatService {
@Resource
private CatRepository catTepository;
@Transactional
public void save(Cat cat){
catTepository.save(cat);
}
@Transactional
public void delete(Cat cat){
catTepository.delete(cat);
}
public Iterable<Cat> findall(Cat cat){
Iterable<Cat> it= catTepository.findAll();
return it;
}
}
f.需要创建一个Controller
@RestController
@RequestMapping("/cat")
public class CatController {
@Resource
private CatService service;
public String findall(){
Cat cat=new Cat();
Iterable<Cat> list=service.findall(cat);
return "show";
}
}
g.代码测试
springboot不需要单独扫注解包
9.spring Data JPA实现持久化操作 详解
(1)Repository接口
这个接口是springData的核心接口,它不提供任何方法,
开发者需要在自己定义的接口中声明需要的方法。
public interface Repository<T,ID extends Serializable>{}
接口说明:repository强调.jpg
(2)CrudRepository接口说明:CrudRepository介绍.jpg
(3)分页排序接口:PagingAndSortingRepository介绍.jpg
(4)其他接口:其他接口.jpg
(5)代码
public interface CatRepository extends CrudRepository<Cat,Integer> {
//注解写sql语句
@Query("from Cat where catname=:cn")
public Cat find(@Param("cn")String catname);
}
(6)分页:实现PagingAndSortingRepository接口
10.springBoot jdbcTemplate
使用步骤:
1.添加依赖
之前引入spring-boot-starter-data-jpa依赖的时候已经默认引入
2.修改dao层接口
public interface UsersDao{
//查询全部
public List findAll();
}
3.使用@Repository注解配置dao层实现类
@Repositorypublic class UsersDaoImpl implements UsersDao { @Autowired private JdbcTemplate jdbcTemplate; @Override public List findAll() { String sql=“select * from users where userid>5”; return jdbcTemplate.query(sql, new RowMapper() { @Override public Users mapRow(ResultSet resultSet, int i) throws SQLException { Users user=new Users(); user.setUserid(resultSet.getInt(“userid”)); user.setUsername(resultSet.getString(“username”)); user.setPassword(resultSet.getString(“password”)); return user; } }); }}
4.测试
11.全局异常捕捉
(1)如何在一个项目中统一处理异常?
步骤:
a.新建一个异常类GlobalException
b.在GlobalException注解上@ControllerAdvice
c.在方法上注解上@ExceptionHandler(value=Exception.class)
补充:
如果返回的是View,自定义的方法的返回值是ModelAndView
如果返回是String 或者JSON格式,那么需要在自定义的方法上添加@ResponseBody注解
示例代码:
@ControllerAdvice
public class GlobalException {
@ExceptionHandler(Exception.class)
@ResponseBody
public String ex(){
return “sorry!!!”;
}
}
12.springBoot之helloWorld访问404
(1) 404-确定地址是否输入正确,启动的控制台查看是否被映射。端口号是否正确
@RestController=@Controller+@ResponseBody
(2) 404-注解是否正确,使用@RestController而不是@Controller
(3) 404-包是否正确,springBoot默认情况下可以扫描到的是@SpringBootApplication
所在的类的同包或者子包下的类
(4) 404-确定引的包是否正确
13.配置server信息
(1)修改端口号,默认8080
修改application.properties文件中添加:
server.port=8888
(2)修改Context-path(之前的访问地址:ip:port/请求名)
在application.properties配置:
server.context-path=/spring-boot
访问地址是:http://ip:port/spring-boot/请求名
注意:属性值后面不要加空格
(3)设定URI的解码字符集
server.tomcat.uri-encoding=utf-8
14.springBoot中使用thymeleaf(模板引擎)
读音:[taīm, li:f ]
步骤:
(1)在pom.xml中引入thymeleaf
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
(2)如何关闭thymeleaf缓存(修改application.properties文件)
#spring.thymeleaf.prefix=classpath:/templates/
#spring.thymeleaf.suffix=.html
#spring.thymeleaf.mode=html5
#spring.thymeleaf.encoding=utf-8
#spring.thymeleaf.content-type=text/html
#取消缓存
spring.thymeleaf.cache=false
(3)编写模板文件.html(模版文件中,html标签需要闭合)
注意:thymeleaf3.0以后,可以不强制闭合
模板文件路径:src/main/resources/templates/demo1.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>Title</title>
</head>
<body>
<h1>demo1.html</h1>
<li th:each="user : ${userlist}">
<span th:text="${user.username}"></span>
</li>
</body>
</html>
(4)编写访问模板文件Controller(这里用的是@Controller)
@Controller
public class TemplateController {
@RequestMapping("/getjson2")
public String test3(ModelMap map){
System.out.println(“test333”);
List users = usersService.getall();
map.addAttribute(“userlist”,users);
return “demo1”;
}
}
15.springBoot freemarker
步骤:
(1)在pom.xml中引入freemarker
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
(2)如何关闭freemarker缓存(修改application.properties)
spring.freemarker.cache=false
补充:
spring.freemarker.prefix= 设置前缀
spring.freemarker.suffix=.ftl 设置后缀
spring.freemarker.template-loader-path=classpath:/templates/ 默认的模板文件的位置
(3)编写模板文件.ftl
位置:src/src/main/resources/templates/hello.ftl
设置静态资源的访问路径
方案1、默认采用springboot 静态资源路径在src/main/resources创建/static 或 /public 或 /resources 或 /META-INF/resources可以直接访问静态资源,默认会放到classpath目录中方案2、通过application.properties配置spring.resources.static-locations=classpath:/img/ 指定自定义静态文件的目录位置,,多个使用逗号分隔,springboot自动失效
实例:
spring.resources.static-locations=classpath:/templates/
(4)编写访问文件的Controller @Controller
@RequestMapping("/hello3")
public String hello3(Map map){
map.put(“k”,value);
return “模板文件名称”;
}
16.springBoot对JSP的支持
实现步骤:
(1)创建Maven Web project
(2)在POM.XML文件中添加依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.5.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<!-- mvc,aop的依赖包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!-- 由于我们在上面指定了parent,这里就不需要指定版本号 -->
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!--tomcat-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.7</java.version>
</properties>
(3)配置application.properties支持jsp
#页面默认前缀目录
spring.mvc.view.prefix=/WEB-INF/jsp/
#响应页面默认后缀
spring.mvc.view.suffix=.jsp
(4)编写测试Controller
@Controller
public class HelloController {
@RequestMapping("/hello")
public String hello(){
return "index";
}
}
(5)编写JSP页面
(6)编写启动类
@SpringBootApplication
public class Test1 {
public static void main(String[] args) {
SpringApplication.run(Test1.class,args);
}
}
注意:编写jsp的时候不要在项目中添加页面静态化的依赖,并且要重新启动服务器,而不是热部署
注意:针对el表达式,对于servlet的版本有限制,2.4版本以下是不支持的,无法进行识别
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns=“http://java.sun.com/xml/ns/javaee”
xsi:schemaLocation=“http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd” version=“2.5”>
解决方式:需要把依赖包中的scope标签去掉
16.springboot集成mybatis
16.1 整合mybatis
实现步骤:
1.添加依赖包
<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.41</version>
</dependency>
2.修改启动文件:
3.创建实体类
4.创建接口
public interface UserMyBatisDao { @Select(“select * from users where username=#{uname}”) public List find(@Param(“uname”) String uname); @Select(“select * from users where username like ‘%${uname}%’”) public List find2( @Param(“uname”) String uname);}注意:集合要加泛型,否则结果集无法映射
5.创建service
6.创建Controller
7.测试
注意:如果报service层中dao层对象没有赋值,说明mapper没有扫描,这可能是jar包引入的问题,需要重新下载依赖包
16.2 设置分页
添加依赖包:
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.0.0</version>
</dependency>
(1)创建配置分页的类
分页参数说明:PageHelper->PageParams
public class PageParams { protected boolean offsetAsPageNum = false; protected boolean rowBoundsWithCount = false; protected boolean pageSizeZero = false; protected boolean reasonable = false; protected boolean supportMethodsArguments = false; protected String countColumn = “0”;}
示例代码:
@Configuration
public class MybatisPageConfig {
@Bean
public PageHelper pg(){
PageHelper pageHelper=new PageHelper();
Properties p=new Properties();
//设置为true时,会将RowBounds第一个参数offset当成pageNum页码使用
//和startPage中的pageNum效果一样
p.setProperty(“offsetAsPageNum”,“true”);
//设置为true时,使用RowBounds分页会进行count查询
p.setProperty(“rowBoundsWithCount”,“true”);
//启用合理化时,如果pageNum<1会查询第一页,如果pageNum>pages会查询最后一页
// 禁用合理化时,如果pageNum<1或pageNum>pages会返回空数据
p.setProperty(“reasonable”,“true”);
pageHelper.setProperties§;
return pageHelper;
}
}
(2)在dao层进行查询之前设置分页
public List find2(String uname,int pageindex) {
PageHelper.startPage(pageindex,3);
Map map=new HashMap();
map.put(“uname”,uname);
return userMyBatisMapper.find2(map);
}
16.3 获得新增数据的id
1.修改sql语句,添加@Options注解
public interface UserMyBatisMapper {
@Insert(“insert into users(username,password) values(#{username},#{password})”)
@Options(useGeneratedKeys = true,keyProperty = “userid”,keyColumn = “userid”)
public int insertUsers(Users users);
2.测试
@RequestMapping("/insertmybatis3")
public String insert(){
Users users=new Users();
users.setUsername(“刘能”);
users.setPassword(“test123”);
myBatisService.insertUser(users);
System.out.println(“新增数据的id=”+users.getUserid());
return “redirect:/testmybatis2?index=1”;
}
16.4 绑定参数异常
错误:
@Select(“select * from users where username like ‘%${uname}%’ and password=#{pass}”)
public List find3( String name, String pass);
处理方式:
@Select(“select * from users where username like ‘%${uname}%’ and password=#{pass}”)
public List find3(@Param(“uname”) String name,@Param(“pass”) String pass);
扫描mapper文件
#mybatis的mapper配置文件
# mybatis配置文件所在路径
mybatis.config-location:classpath:mybatis-config.xml
# 所有的mapper映射文件
mybatis.mapper-locations:classpath*:com/springboot/mapper/*.xml
#给类起别名
mybatis.type-aliases-package=com.qf.entity