SpringBoot的快速入门、热部署、参数处理、WebJars、属性配置、JPA操作数据库、Thymeleaf 模板引擎、JPA+Thymeleaf、RESTful风格、Swagger2构建API等

本文详细介绍了SpringBoot的快速入门,包括Idea中创建项目、配置热部署、处理JSON数据、参数校验、静态资源管理以及WebJars的使用。接着深入讲解了SpringBoot的属性配置,包括默认配置文件、自定义属性读取、实体类属性赋值和多环境配置。在数据库操作方面,详细阐述了SpringBoot如何使用JPA进行数据库操作,如自定义查询、事务管理和分页。同时,文章也探讨了Thymeleaf模板引擎的使用,包括基本操作、对象属性、循环遍历、条件判断和静态资源加载。最后,讨论了如何使用Swagger2构建API文档,以及RESTful风格的API设计。
摘要由CSDN通过智能技术生成

SpringBoot

SpringBoot的简介
  • Spring Boot,其设计目的是用来简化 Spring 应用的初始搭建以及开发过程简化 Maven 配置自动配置 Spring嵌入的 Tomcat,无需部署 WAR 文件,可直接运行
  • Spring家族为微服务提供了一整套的组件,统称为SpringCloud。
  • SpringBoot和微服务紧密联系在一起,是微服务的基石。SpringCloud开发微服务是建立在SpringBoot基础之上的
本文只记录SpringBoot的使用,关于SpringCloud微服务的下一文介绍。

(一)快速入门

(以Idea为例)

1、项目创建,工程主界面如下:


2、编写HelloController.java :

@RestController
public class HelloController {
   
    @GetMapping("/hello")
    public String sayHello() {
   
        return "hello spring Boot!";
    }
}

3、启动SpringbootDemoApplication类main方法:
4、访问http://localhost:8080/hello

  • 项目说明
    • 默认有个xxxApplication类,里面是spring boot的载入函数
    • resources目录下有个application.properties文件,这个是Spring boot的配置文件
      • 这个Spring boot的配置文件又可以改为 application.yml文件(常用的是这种配置)
        • application.yml文件修改tomcat端口等示例(后面说明yml):
    • test目录下有个测试类xxxApplicationTests,这个是spring boot的单元测试
    • pom.xml文件:
      • 一个继承spring-boot-starter-parent
      • 两个依赖,spring-boot-starter-web ,web项目依赖必须
      • spring-boot-starter-test spring boot项目单元测试依赖
    • Springboot程序启动方式
      • 方式一:通过idea直接启动,在启动类上run
      • 方式二:java -jar XX.jar 运行jar包

(二)基本web应用开发

1、SpringBoot 热部署

热部署:在修改项目文件后,不需要重启应用程序,修改之后就可以立刻生效。
配置步骤:
  • 1.1. 添加devtools依赖并开启热部署(修改pom.xml文件)

添加devtools依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
</dependency>

开启热部署

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <!--在原来spring-boot-maven-plugin 追加以下语句:开启热部署-->
    <configuration>
        <fork>true</fork>
    </configuration>
</plugin>
  • 1.2. 开启idea自动make功能
    • CTRL + SHIFT + A --> 查找make project automatically --> 选中 :
      或者点击file --> Settings: --> 选中:
    • CTRL+SHIFT+A查找Registry并勾选compiler.automake.allow.when.app.running:
    • 最后重启idea
  • 1.3. Chrome浏览器中禁用缓存
    • F12 --> NetWork --> Disable Cache(while DevTools is open) :

2、SpringBoot对的json支持

  • @JsonFormat(timezone = “GMT+8”, pattern = “yyyy年MM月dd日 HH时mm分ss秒”)
    • 时间格式化成字符串的格式,即获取时间时会按照该格式返回。
    • GMT 是世界标准时间。中国所在时区就是gmt+8 。
  • @DateTimeFormat(pattern = “yyyy-MM-dd HH:mm:ss”)
    • 字符串格式化成时间的格式,在设置该属性时必须按照以上的格式要求 本例比如:2020-03-03 12:12:12
  • @JsonIgnore
    • 忽略字段,不转换为json
  • @JsonInclude(JsonInclude.Include.NON_NULL)
    • 当属性值为空时候,不转换为json 不为空时转换为json
  • @InitBinder
    • 用来格式化request请求中字符串(2018-01-19 17:25:29)为日期时间类型,如果字符串格式不满足要求,就会报错。
    • @InitBinder就相当于全局的时间格式化注解,而@DateTimeFormat(pattern = “yyyy-MM-dd HH:mm:ss”)只针对类的属性。

使用示例:
新建pojo:Goods.java

package com.offcn.demo.bean;
import java.util.Date;
import org.springframework.format.annotation.DateTimeFormat;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;

public class Goods{
   
	private int id;
	private String name;
	private float price;
	
	//格式化输出,格式化日期时间类型
	//GMT 是世界标准时间。中国所在时区就是gmt+8 。
	@JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd hh:mm:ss")
	@DateTimeFormat(pattern = "yyyy-MM-dd hh:mm:ss")
	private Date createDate;
	
	//忽略字段,不转换为json
	@JsonIgnore
	private String memo;
	//当属性值为空时候,不转换为json
	@JsonInclude(JsonInclude.Include.NON_NULL)
	private String isnull;
	private String email;
	//Set、get方法略
}

创建controller:GoodsController.java

@RestController
public class GoodsController {
   
	@RequestMapping("/getGoods1")
	public Goods getGoods() {
   		
		Goods goods = new Goods();
		goods.setId(1);
		goods.setName("测试");
		goods.setPrice(100000.99F);
		goods.setCreateDate(new Date());
		goods.setMemo("描述");
		goods.setIsnull("不为空显示");
		return goods;
	}
	@InitBinder
	private void initBinder(WebDataBinder webDataBinder){
   
		webDataBinder.addCustomFormatter(new DateFormatter("yyyy-MM-dd HH:mm:ss"));
	}
}

启动访问

3、SpringBoot 请求传递参数

第一类:请求路径传参
  • @RequestParam 获取查询参数。即url?name=value
  • @PathVariable 获取路径参数。即url/{id} 这种形式
@RequestMapping("/getGoods2/{name}")
public Goods getGoodsById(@RequestParam(name="id") Integer id,
							@PathVariable(name="name") String name) {
   		
		Goods goods = new Goods();
		goods.setId(id);
		goods.setName(name);
		goods.setPrice(100000.99F);
		goods.setCreateDate(new Date());
		goods.setMemo("描述");
		goods.setIsnull("不为空显示");
		return goods;
}

第二类:@RequestBody参数
  • @RequestBody注解常用来处理content-type不是默认的application/x-www-form-urlcoded编码的内容,比如说:application/json或者是application/xml等。
  • 常用其来处理application/json类型,后台接收前台的json格式数据。比如说:"{‘title’:‘test’, ‘sub’ : ‘2’}"
@RequestMapping("/getGoods3")
public Goods getGoodsById(@RequestBody Goods goods) {
   
      return goods;
}	
  • 测试:开启postman,设置发出post请求,请求地址getGoods3接口:http://localhost:8080/getGoods3
  • 请求参数,选择body,选择 raw方式,发送JSON(application/json)请求
  • 请求数据数据:{"id":999,"name":"兰博基尼","price":9999.98,"createDate":"2018-12-15 9:18:28","memo":"描述","isnull":"不为空"}
第三类:Body参数(表单)

普通的表单提交方式。

@RequestMapping("/getGoods4")
public Goods getGoodsById(Goods goods) {
   
	return goods;
}	
@InitBinder
private void initBinder(WebDataBinder webDataBinder){
   
	webDataBinder.addCustomFormatter(new DateFormatter("yyyy-MM-dd HH:mm:ss"));
}

4、SpringBoot 参数校验

PathVariable路径参数校验
    //[a-zA-Z0-9_]+ 表达式指定了 group 必须是以大小写字母、数字或下划线组成的字符串。
    @GetMapping("/user/{id:[a-zA-Z0-9_]+}")  
    public String getUserById(@PathVariable String id){
   
        return "根据id查询用户:"+id;
    }

尝试访问地址:http://localhost:8080/user/a8799
http://localhost:8080/user/a87-99

RequestParam请求参数校验
@RestController
@Validated  //开启数据有效性校验,添加在类上即为验证方法,/// 添加在方法参数中即为验证参数对象。
public class UserController {
   
    @GetMapping("/demo123")
    public String user(@NotBlank(message = "id不能为空!") @RequestParam("userid") String id,
                       @NotBlank(message = "name不能为空!") @RequestParam("username") String name,
                       @Email(message = "email格式不正确!") String email){
   
        return id+"==》"+name;
    }
}

测试:http://localhost:8080/valid2?group=&email=11

这里的异常名称叫ConstraintViolationException(违反约束异常)

附带异常的处理:
编写统一异常处理类
处理单个异常:

@ControllerAdvice //增强的 Controller 可以用来 全局异常处理  全局数据绑定和预处理 本示例处理异常
public class GlobalExceptionHandler {
   
	//@ExceptionHandler 是 Controller层面上异常处理注解
    @ExceptionHandler(ConstraintViolationException.class)//参数校验异常
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)  //400 : 参数报错
    public String handleValidationException(ConstraintViolationException e){
   
        String msg = "请求参数不合法,  ";
        for(ConstraintViolation<?> s:e.getConstraintViolations()){
   
            msg += s.getInvalidValue()+": "+s.getMessage() + ";";
        }
        return msg;
    }
}

处理多个异常:

@ControllerAdvice
public class GlobalExceptionHandler {
   
    @ExceptionHandler(Exception.class) //Exception
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String handleValidationException(Exception e){
   
        if(e instanceof ConstraintViolationException ){
   
            ConstraintViolationException exception = (ConstraintViolationException)e;
            for(ConstraintViolation<?> s:exception.getConstraintViolations()){
   
                return s.getInvalidValue()+": "+s.getMessage();
            }
        }else if(e instanceof MethodArgumentNotValidException){
   
            return ((MethodArgumentNotValidException) e).getBindingResult().getFieldError().getDefaultMessage();
        }
        return "请求参数不合法";
    }
}
对象参数校验(表单 pojo) JSR-303 标准的校验
注解 作用
@Validated (重要) 开启数据有效性校验,添加在类上即为验证方法,添加在方法参数中即为验证参数对象。
@NotNull 限制字段必须不为null value != null ? true : false
@NotEmpty 验证注解的元素值不为 null 且不为空,可用在字符串或集合。(字符串长度不为0、集合大小不为0)
@NotBlank 验证注解的元素值不为空(不为null、去除首位空格后长度为0),@NotBlank只应用于字符串且在比较时会去除字符串的空格 value.trim() > 0 ? true : false
@Pattern(value) 限制必须符合指定的正则表达式
@Size(max,min) 限制字符长度必须在 min 到 max 之间(也可以用在集合上)
@Email 验证注解的元素值是Email,也可以通过正则表达式和flag指定自定义的email格式
@Max(value) 限制必须为一个不大于指定值的数字 对应的数据库表字段也会添加一个check的约束条件
@Min(value) 限制必须为一个不小于指定值的数字 同上
@DecimalMax(value) 限制必须为一个不大于指定值的数字 没有上述作用
@DecimalMin(value) 限制必须为一个不小于指定值的数字
@Null 限制只能为null(很少用)
@AssertFalse 限制必须为false (很少用)
@AssertTrue 限制必须为true (很少用)
@Past 限制必须是一个过去的日期
@Future 限制必须是一个将来的日期
@Digits(integer,fraction) 限制必须为一个小数,且整数部分的位数不能超过 integer,小数部分的位数不能超过 fraction (很少用)
@Length 被注释的字符串的大小必须在指定的范围内

示例:
1、修改Goods增加对参数的校验规则

public class Goods {
   
	@Max(value=100,message="id不能大于100")
	private int id;
	
	@NotBlank(message="用户名不能为空")
	@Length(min = 2, max = 10, message = "用户名 长度必须在 {min} - {max} 之间")
	private String name;
	
	@DecimalMin(value="1.0",message="价格最低1元")
	@DecimalMax(value="10.0",message="价格最高10元")
	private float price;
	
	//格式化日期时间类型
	@JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd hh:mm:ss")
	@DateTimeFormat(pattern = "yyyy-MM-dd hh:mm:ss")
	private Date createDate;
	
	//忽略字段,不转换为json
	@JsonIgnore
	private String memo;
	
	//复杂校验
	//当属性值为空时候,不转换为json
	@JsonInclude
	@NotNull(message="属性字段不能为空")
	@NotBlank(message="属性字段不能为空白")
	private String isnull;
	
	@NotBlank(message="手机号不能为空")
	@Pattern(regexp = "^((17[0-9])|(14[0-9])|(13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$",
		    message = "手机号格式不合法")
	private String telephone;
	//验证邮箱格式
	@Pattern(regexp = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$",
	message = "邮箱格式不合法")
	private String email;

	//Set get方法略
}

2、创建Controller

@RestController
public class GoodsValidation {
   
	@RequestMapping("/getGoodsvalidation1")
	public Goods getGoodsvalidation1(@RequestBody @Validated Goods goods) {
   
		return goods;
	}
}

3、

  • 开启postman,设置发出post请求,请求地址:http://localhost:8080/getGoodsvalidation1
  • 请求参数,选择body,选择 raw方式,发送JSON(application/json)请求
  • 请求数据数据1:{"id":999,"name":"你好","price":8.98,"createDate":"2018-12-15 9:18:28","memo":"描述","isnull":"不为空"}

5、SpringBoot 静态资源

默认静态资源映射
  • Spring Boot 默认将 /** 所有访问映射到以下目录:
    • classpath:/static
    • classpath:/public
    • classpath:/resources (resources下创建的resources目录)
    • classpath:/META-INF/resources
  • 示例:
    • 如:在resources目录下新建 public、resources、static 三个目录并分别放入 a.jpg b.jpg c.jpg 图片
    • 浏览器分别访问:http://localhost:8080/a.jpg 、http://localhost:8080/b.jpg、http://localhost:8080/c.jpg均正常访问。
自定义静态资源目录访问
第一种方式
  • 1、配置类(Springboot推荐使用java的方式做配置)、注意::@Configuration注解 ==== applicationContent.xml
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
   
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
   
        // 将所有D:\\springboot\\pic\\   访问都  映射到 /myPic/**   路径下
		registry.addResourceHandler("/myPic/**").addResourceLocations("file:D:\\springboot\\pic\\");
    }
}
  • 示例:在D:/springboot/pic/中有一张logo.jpg图片,重启项目后,在浏览器输入:http://localhost:8080/myPic/logo.jpg即可访问
第二种方式
  • 配置application.properties
web.upload-path=D:/springboot/pic/
spring.mvc.static-path-pattern=/**
spring.resources.static-locations=classpath:/a/b/,classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${
   web.upload-path}
# 注意:
# web.upload-path:这个属于自定义的属性,指定了一个路径,注意要以/结尾;
# spring.mvc.static-path-pattern=/**:表示所有的访问都经过静态资源路径;
# spring.resources.static-locations:在这里配置静态资源路径,
# 这里的配置是覆盖默认配置,所以需要将默认的也加上,
# 否则static、public等这些路径将不能被当作静态资源路径,
# 在这个最末尾的file:${web.upload-path}之所以要加file:是因为指定的是一个具体的硬盘路径,
# 其他的使用classpath指的是系统环境变量。

6、WebJars:以jar包方式打包的web资源(jquery,bootstrap等)。

  • 在SpringBoot中,允许我们直接访问WEB-INF/lib下的jar包中的/META-INF/resources目录资源,即WEB-INF/lib/{*.jar}/META-INF/resources下的资源可以直接访问
  • WebJars也是利用了此功能,将所有前端的静态文件(如jQuery & Bootstrap)打包成一个jar包,和普通的jar引入是一样的,还能很好的对前端静态资源进行管理
使用示例:

1、添加jquery和Bootstrap的webjars依赖 如需其他,WebJars查询:https://www.webjars.org/all

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>jquery</artifactId>
    <version>3.3.1-1</version>
</dependency>
<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>bootstrap</artifactId>
    <version>4.2.1</version>
</dependency>

  • 如图:

  • 可以了解到静态文件存放规则:META-INF/resources/webjars/${name}/${version}

2、html引入:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--引入jquery-->
    <script src="webjars/jquery/3.3.1-1/jquery.js"></script>
</head>
<body>
	<div align="center">
		我的第一个springboot应用
	</div>
	<script>
	    $(function () {
    
	        alert("jquery生效")
	    })
	</script>
</body>
</html>

(三)SpringBoot属性配置

  • Spring Boot并不是『零配置』,它的理念是“习惯优于配置”采用了一些默认的习惯性配置,让你无需手动进行配置,从而让你的项目快速运行起来。所以要想玩转Spring Boot,了解这些默认配置还是必不可少的。

1、默认属性配置文件

  • 创建Spring Boot项目时,在src/main/resources目录下,会默认生成一个全局配置文件application.properties(可以修改后缀为.yml)
  • 注意:application.yml和application.properties编写的格式不一样
  • yml语法:
    • k: v 表示键值对关系,冒号后面必须有一个空格
    • 使用空格的缩进表示层级关系,左对齐的一列数据,都是同一个层级的

修改tomcat端口和访问路径示例:

server:
  port: 8888
  servlet:
    context-path: /java001

2、自定义属性及读取

  • 自定义属性简单赋值
  • 1、application.yml文件中,配置常量:
server:
  port: 8088
  servlet:
    context-path: /java001
my_ip: 1.1.1.1
my_port: 9999
  • 2、编写Controller类读取自定义属性:
@RestController
public class HelloConfigController {
   

	@Value("${server.port}")
	String port;
	@Value("${my_ip}")
	private String ip;
	@Value("${my_port}")
	private String port;
	
	@GetMapping("/getvalue")
	public String getValue() {
   
		return port +","+ ip +","+ port;
	}
}

浏览器访问:http://localhost:8088/getvalue

3、实体类属性赋值

  • 若属性参数变多的时候,习惯创建一个实体,用实体来统一接收这些属性值。

(1)、定义配置文件

userbody:
  name: me
  password: 123456
  birthday: 1992.10.28
  mobile: 13812345678
  address: 北京市朝阳区

(2)、创建实体类

//需要在实体类上增加注解@ConfigurationProperties,并指定prrfix前缀。
@ConfigurationProperties(prefix="userbody")
public class UserBody {
   
	    private String name;
	    private String password;
	    private String birthday;
	    private String mobile;
	    private String address;
	    //Setget方法略
}

(3)、编写Controller注入属性bean

@RestController
@EnableConfigurationProperties({
   UserBody.class})
public class HelloControllerBean {
   
	@Autowired
	UserBody userbody;

    @GetMapping("/getUser")
    public String getUser(){
   
        return userbody.toString();
    }
}

浏览器访问:http://localhost:8088/getUser

4、自定义配置文件

  • application.yml/application.properties是系统默认的配置文件(只能写一个)
  • 但也可以创建自定义配置文件,在路径src/main/resources下面创建文件test.properties/yml
  • 注意:spring boot 1.5版本后@PropertySource注解就不能加载自定义的yml配置文件了,但可以加载properties

1、定义test.properties

testuser.name = me
testuser.password = 123
testuser.birthday = 1978.10.28

2、将配置赋值到javabean

@Configuration
@PropertySource("classpath:test.properties")
@ConfigurationProperties(prefix = "testuser")
public class TestUser {
   
	private String name;
    private String password;
    private String birthday;
	//Set get方法略
}

3、Controller 读取配置

@RestController
@EnableConfigurationProperties({
   TestUser.class})
public class TestController {
   
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值