springboot介绍以及整合的组件

一、 SpringBoot

1.1 什么是 springboot

Spring Boot是由Pivotal团队提供的全新工具集,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,Spring Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者。

spring大家都知道,boot是启动的意思。所以,spring boot其实就是一个启动spring项目的一个工具而已。从最根本上来讲,Spring Boot就是一些库的集合,它能够被任意项目的构建系统所使用。
以前在写spring项目的时候,要配置各种xml文件,还记得曾经被ssh框架支配的恐惧。随着spring3,spring4的相继推出,约定大于配置逐渐成为了开发者的共识,大家也渐渐的从写xml转为写各种注解,在spring4的项目里,你甚至可以一行xml都不写。

虽然spring4已经可以做到无xml,但写一个大项目需要茫茫多的包,maven配置要写几百行,也是一件很可怕的事。

现在,快速开发一个网站的平台层出不穷,nodejs,php等虎视眈眈,并且脚本语言渐渐流行了起来(Node JS,Ruby,Groovy,Scala等),spring的开发模式越来越显得笨重。

在这种环境下,spring boot伴随着spring4一起出现了。
springboot 的使用很简单,我们只需要将原先我们的 xml 配置中的内容通过 java 方式配置过去即可,大部分配置已经被 springboot 自己装配,我们只需要将需要我们自己写的配置单独写出来即可

1.2 hello world

基于 springBoot 快速搭建web项目

maven3.2+;java1.8+;spring-boot-2.x;

1.2.1 安装springboot

安装很简单:一个父pom,一个依赖,一个插件

<!-- === 1) 指定父pom === 
	 继承spring-boot-starter-parent 
     springBoot运行中需要很多依赖和插件,springBoot给出了父pom,用于帮助用户使用这些依赖和插件。
     其中做了依赖管理,插件管理:在导入依赖和插件时可以不用定义version和参数配置,都由父pom统一管理
	 只需要定义groupId和artifactId即可。
-->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.3.RELEASE</version>
</parent>
<!-- === 2) 导入 springboot 的 web 依赖 === 
	 此处不需要添加版本,由 parent 统一管理 
     为项目添加web的依赖:主要是引入springMVC的依赖,和引入内置的tomcat
-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 至此,就已经用了springBoot的两个start啦:【spring-boot-starter-parent】
                                      	  【spring-boot-start-web】
     sprngBoot中提供了很多start,用于支持不同功能的自动配置。即在使用springBoot时,可根据不同的需要导
     入不同的start,springBoot根据项目中引入的不同的start,完成对应的自动配置。 
-->
<!-- === 3) 添加 springboot plugin ===
	 提供springboot的maven支持,导入此插件后,就可以通过maven打包springboot项目
     生成 “executable jars”
	 还提供了spring-boot:run功能,可以启动springboot项目(和main函数功能相似)
-->
<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
1.2.2 启动类

1) 自定义启动类:BootApplication

2) 定义一个Controller类:UserController

注意启动类建议在Controller类所在包的父包中

package com.rj;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;

//@EnableAutoConfiguration //自动装载配置 根据项目中导入的 start 自动装载配置
//@ComponentScan //扫描当前包和所有子包的所有类
@SpringBootApplication
public class BootApplication {
   
    public static void main(String[] args) {
   
        //项目启动,启动工厂,启动tomcat,部署项目
        SpringApplication.run(SpringApplication.class,args);
    }
}
package com.rj.controller;
...

@Controller
public class UserController {
   
    @RequestMapping("helloworld")
    @ResponseBody
    public String helloWorld() {
   
        return "hello moto";
    }
}
1.2.3 启动项目
* 启动方式1:
* 直接运行 入口类的 main 方法即可
* 启动方式2:
* mvn spring-boot:run
1.2.4 访问项目
* 正常访问即可 http://localhost:8080/helloworld
* 注意:路径中没有项目名

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gmKssjyD-1576236354666)(mdpic/2.png)]

1.2.5 springboot-配置

在resources下建立springboot的配置文件:application.yml 或 application.properties

重启项目,配置即可生效。

# application.yml ( 通过tab缩进区分级别,:后要有一个空格然后再定义值 )
server:
  # tomcat端口 , 默认 “8080”
  port: 8989
  # 项目部署名(上下文名称),默认 “/”
  servlet:
    context-path: /fruit9
  tomcat:
  	# 防止get请求参数中文乱码,默认 “utf-8”
    uri-encoding: utf-8
# application.properties
server.port=8989
server.tomcat.uri-encoding=utf-8
server.servlet.context-path=/boot

二、SpringMVC细节

2.1 拦截器

2.1.1 定义拦截器

与原先的使用方式一致

2.1.2 配置拦截器

项目中不再出现mvc的配置文件,更建议的配置方式基于类的。

@Configuration
public class SpringMVCConfig implements WebMvcConfigurer{
   //继承 WebMvcConfigurer
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    //添加自定义拦截器
        //注册 拦截器
        registry.addInterceptor(new MyInterceptor()) //注册拦截器
                .addPathPatterns("/user/*","/user/test3/a"); //定义拦截路径
    }
}

2.2 Json处理

默认采用的依然是Jackson。

相关注解:@RestController @ResponseBoby @RequestBody 使用照旧。

如果要使用FastJson,则需要配置如下:

@Configuration
public class SpringMVCConfig implements WebMvcConfigurer{
   
	.....
    
    // 注册FastJsonHttpMessageConverter
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
   
        // 1. 定义一个converters转换消息的对象
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        // 2. 获取配置对象
        FastJsonConfig fastJsonConfig = fastConverter.getFastJsonConfig();
        // 2.1 全局设置日期格式
        fastJsonConfig.setDateFormat("yyyy-MM-dd HH");
        // 2.2 null值,依然写出。默认忽略null值
        fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteMapNullValue);
        // 3. 设置支持的数据格式
        fastConverter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON_UTF8));
        converters.add(0,fastConverter);//将FastJson的HttpMeesageConverter置在Jackson之前,使其生效
    }
}
@Configuration
public class FastJsonConf {
   
    /**
    	HttpMessageConvertersAutoConfiguration是负责做Converters自动注册的组件,其中:
    	@Bean
        @ConditionalOnMissingBean //此注解含义:如果工厂中没有定义名为"httpMessageConverters"
                                  //          或类型为"HttpMessageConverters"的bean,则执行如下自动装配
        public HttpMessageConverters messageConverters() {
            return new HttpMessageConverters(
                    this.converters != null ? this.converters : Collections.emptyList());
        }
        所以有如下类型为 HttpMessageConverters的bean,会使得此项自动装配失效
    */
    @Bean
    public HttpMessageConverters fastJsonHttpMessageConverters() {
   //更方便的注册HttMessageConverter的方式
        // 1. 定义一个converters转换消息的对象
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        // 2. 获取配置对象
        FastJsonConfig fastJsonConfig = fastConverter.getFastJsonConfig();
        // 设置日期格式
        fastJsonConfig.setDateFormat("yyyy-MM-dd HH");
        // null值,依然写出。默认忽略null值
        fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteMapNullValue);
        // 设置支持的数据格式
        fastConverter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON_UTF8));
        // 3. 返回HttpMessageConverters对象
        return new HttpMessageConverters(fastConverter);
    }
}

2.3 Rest支持

已注册好:OrderedHiddenHttpMethodFilter,用户供浏览器发请求时,模拟put和delete请求。

已注册好:OrderedHttpPutFormContentFilter,用在在put请求中发送 application/x-www-form-urlencoded编码的参数

2.4 跨域

此注解只有在Controller类上才有效

@CrossOrigin(value = "http://localhost:8080",allowCredentials = "true")

或者也可以定义配置

@Configuration
public class MVCConfig implements WebMvcConfigurer{
   
    ....
    //设置跨域
    public void addCorsMappings(CorsRegistry registry) {
   
        registry.addMapping("/**").allowedOrigins("http://localhost:8080").allowCredentials(true);
    }
}

2.5 静态资源

自动注册了静态资源处理的handler,ResourceHttpRequestHandler 其requestMapping为 【/**

用于处理静态资源,所以静态资源已经自动解决。

webapp目录下的静态资源可以正常访问。

新增静态资源目录:‘resources’下新建 static目录,static中存放静态资源 ( ResourceProperties 管理此目录)

访问:http://ip:port/contextPath/js/aa.js http://ip:port/contextPath/png/boot.jpg 访问:<script src="/contextPath/js/aa.js"> </script> <img src="/contextPath/png/boot.jpg"/>
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ezi1K5ef-1576236355695)(mdpic/static_resource.png)]
webapp下的静态资源访问路径 照旧!但此时可以不定义webapp目录!

2.6 异常解析器

如果出现服务器错误,即,服务器端出现异常,此时有两种选择:

1> 各个方法中添加 try... catch...

2> 定义异常解析器,做全局的异常处理

@ControllerAdvice
public class MyExceptionResolver {
   

    /**
     * 可选参数: request response session model
     * 可选返回值: String ResponseBody ModelAndView void
     */
    @ExceptionHandler(value={
   MyException1.class,MyException2.class}) //定义要捕获的异常,一个或多个
    public String handleEx1(HttpServletRequest request, HttpServletResponse res, HttpSession session, 
                            Exception e){
   
        System.out.println(e.getClass()+e.getMessage());
        return "forward:/error.html";
    }
    @ExceptionHandler(value={
   UnknownAccountException.class, IncorrectCredentialsException.class})
    @ResponseBody
    public R handleExLoginError(HttpServletRequest request, HttpServletResponse res, HttpSession session,
                      Exception e){
   
        e.printStackTrace();
        return R.error("登录失败");// R是自定义的工具类
    }

    /* 了解:另一种形式
    @ExceptionHandler//如果注解中没指定注解,则参数表中最后一个参数被认为是 需要捕获的异常(只能定义一个异常)
    public String handleEx1(HttpServletRequest request, HttpSession session,MyException1 e1){
        System.out.println(e1);
        return "forward:/error.html";
    }*/
}

2.7 上传解析器

不用再手动注册上传解析器,自动注册了,StandardServletMultipartResolver, 且其并不依赖 commons-fileupload。如果需要限定上传文件大小,可做如下配置:

spring:
  servlet:
    multipart:
      max-request-size: 10000MB #请求最大容许体量
      max-file-size: 10000MB #文件容许体量
      #如上两个都设置大值,然后在通过拦截器过滤大小并抛异常,在配合异常解析器即可。
//提交表单 照旧
//接收请求的handler 照旧
//异常解析器,添加一个ExceptionHandler,用于处理文件超大问题
@ControllerAdvice
public class MyExceptionResolver {
   

    @ExceptionHandler(value={
   MaxUploadSizeExceededException.class}) //定义要捕获的异常,一个或多个
    public String handleUpload(HttpServletRequest request, HttpServletResponse res, HttpSession session, 
                               Exception e){
   
        System.out.println(e.getClass()+e.getMessage());
        return "redirect:/error.html"
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是SpringBoot整合EasyExcel模板导出Excel的步骤: 1.创建SpringBoot项目 2.在pom.xml文件中添加EasyExcel依赖 ```xml <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>2.1.6</version> </dependency> ``` 3.创建Excel模板 4.编写实体类,用于映射Excel中的数据 5.编写Excel导出工具类 ```java public class ExcelUtil { /** * 导出 Excel :一个 sheet,带表头. * * @param sheetName sheet 名称 * @param clazz 实体类对象,通过 annotation 设置标题 * @param data 实体类对象数据 list * @param out 输出流 */ public static void exportExcel(String sheetName, Class clazz, List data, OutputStream out) { ExcelWriter writer = EasyExcelFactory.getWriter(out); //写第一个sheet,sheet1 数据全是List<String> 无模型映射关系 Sheet sheet = new Sheet(1, 0, clazz); sheet.setSheetName(sheetName); //设置自适应宽度 sheet.setAutoWidth(Boolean.TRUE); //写数据到 Writer 上下文中 writer.write(data, sheet); //将上下文中的最终 outputStream 写入到指定文件中 writer.finish(); } } ``` 6.在Controller中调用Excel导出工具类 ```java @GetMapping("/export") public void export(HttpServletResponse response) throws IOException { //查询数据 List<User> userList = userService.getUserList(); //设置文件名 String fileName = "用户信息表"; //设置响应头 response.setContentType("application/vnd.ms-excel"); response.setCharacterEncoding("utf-8"); response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx"); //导出Excel ExcelUtil.exportExcel(fileName, User.class, userList, response.getOutputStream()); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值