Springboot
1 快速入门
1.1 常用注解
-
@Controller 作用:用于标记这个类是一个控制器,返回页面的时候使用;如果要返回JSON,则需要在接口上使用@ResponseBody才可以
-
@RestController 作用:用于标记这个类是一个控制器,返回JSON数据的时候使用,如果使用这个注解,则接口返回数据会被序列化为JSON
所以:@RestController = @Controller+@ResponseBody -
@RequestMapping 作用:路由映射,用于类上做1级路径;用于某个方法上做子路径
-
@SpringBootApplication 作用: 用于标记是SringBoot应用,里面包含多个子注解,即
@SpringBootApplication = @Configuration+@EnableAutoConfiguration+@ComponentScan
(下面的目前只需简单理解即可,想深入的同学,后续可以看专门的Spring原理课程深入)
@Configuration: 主要标注在某个类上,用于spring扫描注入,一般结合@Bean使用
@EnableAutoConfiguration: 启用Spring的自动加载配置,自动载入应用程序所需的所有Bean
@ComponentScan:告诉spring扫描包的范围,默认是Applocation类所在的全部子包,可以指定其他包
@ComponentScan({"net.xdclass.package1","net.xdclass.package2"})
2 开发规范
2.1 SpringBoot目录文件结构和官方推荐的目录规范、静态资源访问
目录讲解
src/main/java:存放代码
src/main/resources
static: 存放静态文件,比如 css、js、image, (访问方式 http://localhost:8080/js/main.js)
templates:存放静态页面jsp,html,tpl
config:存放配置文件,application.properties
resources:
同个文件的加载顺序,静态资源文件 Spring Boot 默认会挨个从
META/resources >resources >static >public
里面找是否存在相应的资源,如果有则直接返回,不在默认加载的目录,则找不到
默认配置
spring.resources.static-locations = classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
基本互联网企业 静态资源文件存储在CDN ,HTML、CSS、图片等
CDN : 内容分发网络
文件服务器: 阿里云OSS
2.2 SpringBoot目录文件结构和官方推荐的目录规范
注意:应用启动的位置,Application启动类位置
三种形式
- 当启动类和controller在同一类中时,在该类上添加注解@Controller即可;
- 当启动类和controller分开时,启动类要放在根目录下,启动类上只需要注解@SpringBootApplication;
- 当启动类和controller分开时,如果启动类在非根目录下,需要在启动类中增加注解@ComponentScan,并配置需要扫描的包名,如(basePackages = )
@ComponentScan(basePackages ={“net.xdclass.controller”,“net.xdclass.service”})
工作中用哪种比较多?
强烈推荐第二种方式,不然漏配置扫描包,项目庞大,出现问题则难排查
3 核心模块
3.1 SpringBoot2.X开发HTTP接口GET请求
- GET请求
场景:一般的查询接口就是get请求
注解:@GetMapping = @RequestMapping(method = RequestMethod.GET) - 一个顶两的注解
@GetMapping = @RequestMapping(method = RequestMethod.GET)
@PostMapping = @RequestMapping(method = RequestMethod.POST)
@PutMapping = @RequestMapping(method = RequestMethod.PUT)
@DeleteMapping = @RequestMapping(method = RequestMethod.DELETE)
3.2 SpringBoot2.X统一接口返回协议-掌握开发规范
- 存在的问题:协议未统一,缺少业务状态码
- JSONData工具类开发
public class JsonData {
private int code;
private Object data;
private String msg;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public JsonData(){}
public JsonData(int code, Object data){
this.code = code;
this.data = data;
}
public JsonData(int code, Object data, String msg){
this.code = code;
this.data =data;
this.msg = msg;
}
public static JsonData buildSuccess(Object data){
return new JsonData(0,data);
}
public static JsonData buildError(String msg){
return new JsonData(-1,"",msg);
}
public static JsonData buildError(String msg,int code){
return new JsonData(code,"",msg);
}
}
3.3 SpringBoot2.X开发HTTP接口POST请求
- POST请求-form表单
场景:表单提交,如果不用细分PUT/DELETE方法,则都可以用POST
注解:@PostMapping = @RequestMapping(method = RequestMethod.POST)
-
开发功能:账号密码提交登录接口,form表单形式
-
POST请求-RequestBody方式
场景:json对象映射,数组对象提交接口开发
注解:@PostMapping = @RequestMapping(method = RequestMethod.POST)
- 开发功能:新增视频json对象,章数组提交
4 热部署
4.1 什么是热部署
-
什么是热部署
应用正在运行的时候升级功能, 不需要重新启动应用
对于Java应用程序来说, 热部署就是在运行时更新Java类文件
好处:不需要重新手工启动应用,提高本地开发效率 -
常见实现热部署的方式
Jrebel Spring Loaded spring-boot-devtools
4.2 配置文件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork><!--必须添加这个配置-->
</configuration>
</plugin>
</plugins>
</build>
5 SpringBoot.2.X里面的配置文件
5.1 版SpringBoot注解配置文件映射属性和实体类
官方文档配置:
https://docs.spring.io/spring-boot/docs/2.3.0.BUILD-SNAPSHOT/reference/htmlsingle/#core-properties
配置文件加载
方式一:
1、Controller上面配置 @PropertySource({“classpath:resource.properties”})
2、增加属性 @Value("${test.name}") private String name;
方式二:实体类配置文件
1、添加 @Component 注解;
2、使用 @PropertySource 注解指定配置文件位置;
3、使用 @ConfigurationProperties 注解,设置相关属性;
4、必须 通过注入IOC对象Resource 进来 , 才能在类中使用获取的配置文件值。
@Autowired private ServerSettings serverSettings;
例子:
@Configuration
@ConfigurationProperties(prefix="test")
@PropertySource(value="classpath:resource.properties")
public class ServerConstant {
}
常见问题:
1、配置文件注入失败,Could not resolve placeholder
解决:根据springboot启动流程,会有自动扫描包没有扫描到相关注解,
默认Spring框架实现会从声明@ComponentScan所在的类的package进行扫描,来自动注入,
因此启动类最好放在根路径下面,或者指定扫描包范围
spring-boot扫描启动类对应的目录和子目录
2、注入bean的方式,属性名称和配置文件里面的key一一对应,就用加@Value 这个注解
如果不一样,就要加@value("${XXX}")
6 Springboot2.X单元测试应用
6.1 公司里面软件开发测试流程
需求分析->设计->开发->测试->上线
测试里面的种类
- 单元测试:完成最小的软件设计单元的验证工作,目标是确保模块被正确的编码
- 黑盒测试:不考虑内部结构,主要测试功能十分满足需求
- 白盒测试:针对代码级别,测试开发工程师一般具备白盒测试能力,针对程序内部的逻辑结构进行- 代码级别的测试
- 回归测试:对原先提出的缺陷进行二次验证,开发人员修复后进行二次的验证
- 集成测试:测试模块和模块之间的整合,且测试主要的业务功能
- 系统测试:针对整个产品系统进行的测试,验证系统是否满足产品业务需求
6 .2 怎么用SpringBoot2.x的单元测试
- 相关依赖
!--springboot程序测试依赖,如果是自动创建项目默认添加-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
- 配置相关注解
@RunWith(SpringRunner.class) //底层用junit SpringJUnit4ClassRunner
@SpringBootTest(classes={XdclassApplication.class})//启动整个springboot工程
public class SpringBootTests { }
-
常用单元测试的注解
@before
@Test
@After -
断言:判断程序结果是否符合预期 TestCase.assertXXX
6.3 单元测试调用Controller-Service层接口
- Controller层登录方法测试
@Autowired
private UserController userController;
@Test
public void loginTest(){
User user = new User();
user.setUsername("jack");
user.setPwd("1234");
JsonData jsonData = userController.login(user);
System.out.println(jsonData.toString());
TestCase.assertEquals(0,jsonData.getCode());
}
6.4 pringboot的MockMvc调用api层接口
-
如何测试Controller对外提供的接口
增加类注解 @AutoConfigureMockMvc
注入一个MockMvc类 -
相关API :
perform执行一个RequestBuilder请求
andExpect:添加ResultMatcher->MockMvcResultMatchers验证规则
andReturn:最后返回相应的MvcResult->Response
@Autowired
private MockMvc mockMvc;
@Test
public void testVideoListApi()throws Exception{
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/pub/video/list"))
.andExpect(MockMvcResultMatchers.status().isOk()).andReturn();
int status = mvcResult.getResponse().getStatus();
System.out.println(status);
//会乱码
//String result = mvcResult.getResponse().getContentAsString();
// 使用下面这个,增加 编码 说明,就不会乱码打印
String result = mvcResult.getResponse().getContentAsString(Charset.forName("utf-8"));
System.out.println(result);
}
7 Springboot2.X全局异常处理
7.1 SpringBoot2.X全局异常处理
- 为什么要配置全局异常?
不配全局服务端报错场景 1/0、空指针等 - 配置好处
1.统一的错误页面或者错误码
2.对用户更友好
- Springboot2.X怎么在项目中配置全局异常
类添加注解:
@ControllerAdvice,如果需要返回json数据,则方法需要加@ResponseBody
@RestControllerAdvice, 默认返回json数据,方法不需要加@ResponseBody
方法添加处理器:
捕获全局异常,处理所有不可知的异常
@ExceptionHandler(value=Exception.class)
7.2 SpringBoot自定义异常和错误页面跳转实战
- 返回自定义异常界面,需要引入thymeleaf依赖(非必须,如果是简单的html界面则不用)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
- resource目录下新建templates,并新建error.html
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("error.html");
modelAndView.addObject("msg", e.getMessage());
return modelAndView;
8 新版Servlet3.0和SpringBoot2.X过滤器-拦截器
8.1 SpringBoot2.X过滤器
-
什么是过滤器
filter简单理解:人—>检票员(filter)—> 景点 -
SpringBoot2.X里面的过滤器
ApplicationContextHeaderFilter
OrderedCharacterEncodingFilter
OrderedFormContentFilter
OrderedRequestContextFilter
- 那么多过滤器,哪个优先级高呢?
Ordered.HIGHEST_PRECEDENCE Ordered.LOWEST_PRECEDENCE
低位值意味着更高的优先级 Higher values are interpreted as lower priority
- 自定义Filter,避免和默认的Filter优先级一样,不然会冲突
- 注册Filter配置两种方式
bean FilterRegistrationBean
Servlet3.0 webFileter
8.2 使用Servlet3.0注解开发自定义的过滤器
1.使用Servlet3.0的注解进行配置步骤
- 启动类里面增加 @ServletComponentScan,进行扫描
- 新建一个Filter类,implements Filter,并实现对应的接口
- @WebFilter 标记一个类为filter,被spring进行扫描
- urlPatterns:拦截规则,支持正则
- 控制chain.doFilter的方法的调用,来实现是否通过放行
- 不放行,web应用resp.sendRedirect("/index.html") 或者 返回json字符串
2.场景:权限控制、用户登录状态控制,也可以交给拦截器处理等
3.案例:用户登录过滤器
8.3 自定义Filter 未登录json错误码提示开发
private void renderJson(HttpServletResponse response,String json){
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
try(PrintWriter writer = response.getWriter()){
writer.print(json);
}catch (Exception e){
e.printStackTrace();
}
}
8.4 ervlet3.0+SpringBoot2.X 注解Listener常用监听器
-
监听器:应用启动监听器,会话监听器,请求监听器
-
作用:
ServletContextListener 应用启动监听
HttpSessionLisener 会话监听
ServletRequestListener 请求监听 -
常用的监听器 ServletContextListener、HttpSessionListener、ServletRequestListener)
@WebListener
public class RequestListener implements ServletRequestListener {
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("======contextDestroyed========");
}
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("======contextInitialized========");
}
}
8.5 pingboot2.x新版本配置拦截器在项目中的使用
SpringBoot2.X 新版本配置拦截器 implements WebMvcConfigurer
自定义拦截器 HandlerInterceptor
preHandle:调用Controller某个方法之前
postHandle:Controller之后调用,视图渲染之前,如果控制器Controller出现了异常,则不会执行此方法
afterCompletion:不管有没有异常,这个afterCompletion都会被调用,用于资源清理
按照注册顺序进行拦截,先注册,先被拦截
9 新版SpringBoot2.X 整合模板引擎thymeleaf和Fk
9.1 SpringBoot2.x的starter和常见模板引擎讲解
JSP(后端渲染,消耗性能)
Java Server Pages 动态网页技术,由应用服务器中的JSP引擎来编译和执行,再将生成的整个页面返回给客户端
可以写java代码
持表达式语言(el、jstl)
内建函数
JSP->Servlet(占用JVM内存)permSize
javaweb官方推荐
springboot官方不推荐
Freemarker
FreeMarker Template Language(FTL) 文件一般保存为 xxx.ftl
严格依赖MVC模式,不依赖Servlet容器(不占用JVM内存)
内建函数
Thymeleaf (主推)
轻量级的模板引擎(复杂逻辑业务的不推荐,解析DOM或者XML会占用多的内存)
可以直接在浏览器中打开且正确显示模板页面
直接是html结尾,直接编辑xdlcass.net/user/userinfo.html
社会工程学伪装
9.2 SpringBoot2.x整合模板引擎freemarker
- Freemarker相关maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
- Freemarker基础配置
# 是否开启thymeleaf缓存,本地为false,生产建议为true
spring.freemarker.cache=false
spring.freemarker.charset=UTF-8
spring.freemarker.allow-request-override=false
spring.freemarker.check-template-location=true
#类型
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=true
spring.freemarker.expose-session-attributes=true
#文件后缀
spring.freemarker.suffix=.ftl
#路径
spring.freemarker.template-loader-path=classpath:/templates/
- 建立文件夹
1)src/main/resources/templates/fm/user/
2)建立一个index.ftl
3)user文件夹下面建立一个user.html
9.3 SpringBoot2.X整合模板引擎thymeleaf
- 官网地址:https://www.thymeleaf.org/doc/articles/thymeleaf3migration.html
- thymeleaf相关maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
- thymeleaf基础配置
#开发时关闭缓存,不然没法看到实时页面
spring.thymeleaf.cache=false
spring.thymeleaf.mode=HTML5
#前缀
spring.thymeleaf.prefix=classpath:/templates/
#编码
spring.thymeleaf.encoding=UTF-8
#类型
spring.thymeleaf.content-type=text/html
#名称的后缀
spring.thymeleaf.suffix=.html
- 建立文件夹
1)src/main/resources/templates/tl/
2)建立一个index.html
- 简单测试代码编写
注意:$表达式只能写在th标签内部
快速入门:https://www.thymeleaf.org/doc/articles/standarddialect5minutes.html