SpringBoot

springboot创建的两种方式:
一: 手动创建: springboot内置tomcat所以可以直接创建jar项目,
1.配置依赖

<!--继承spring-boot-starter-parent 主要目的:1. 配置文件 2. 插件3.依赖jar-->
   <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.13.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
     <!--引入springmvc启动器-->
       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

( 如果springboot使用了继承就不能再继承其他项目了 所以springboot还提供了依赖的方式

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>2.1.13.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

)
2.新建启动类

@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class,args);
    }
}

就可以直接运行了

启动类中@SpringBootApplication这个注解中包含了三个关键的注解
① @SpringBootConfiguration: 标注改类是个配置类
② @EnableAutoConfiguration:自动配置
③ @ComponentScan : 注解扫描

二:使用IDEA自动创建springboot 通过spring Initializr自动创建
创建时选择

SpringBoot 整合

1.springboot整合Mybatis
①配置依赖启动器

<!--springboot整合mybatis依赖启动器-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.1</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.11</version>
</dependency>

②配置文件连接数据库

# mybatis 配置
spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/maven?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8
username: root
    password: root
driver-class-name: com.mysql.cj.jdbc.Driver
# 加载MyBatis的mapper.xml
mybatis:
  mapper-locations: classpath:mybatis/*.xml
# 设置实体类的别名
  type-aliases-package: com.bjsxt.pojo

③在启动类上添加@MapperScan(“com.bjsxt.mapper”) 或者在mapper层的方法上加@Mapper
告诉启动器扫描mapper
注意:mapper.xml要写在resources目录下的mybatis文件内 与连接数据库的配置保持一致

2.springboot整合Druid(使用数据库连接池技术)
①添加依赖启动器

<!--springboot整合groupld依赖启动器-->
<dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
        <version>1.1.10</version>
    </dependency>

②添加配置文件

spring:
  datasource:
    # 使用阿里的Druid连接池
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    # 填写你数据库的url、登录名、密码和数据库名
    url: jdbc:mysql://127.0.0.1:3306/tingyu?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8
username: root
    password: root
    druid:
      # 连接池的配置信息
      # 初始化大小,最小,最大
      initial-size: 5
      min-idle: 5
      maxActive: 20
      # 配置获取连接等待超时的时间
      maxWait: 60000
      # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
      timeBetweenEvictionRunsMillis: 60000
      # 配置一个连接在池中最小生存的时间,单位是毫秒
      minEvictableIdleTimeMillis: 300000
      validationQuery: SELECT 1
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      # 打开PSCache,并且指定每个连接上PSCache的大小
      poolPreparedStatements: true
      maxPoolPreparedStatementPerConnectionSize: 20
      # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
      filters: stat,wall,slf4j
      # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
      connectionProperties: druid.stat.mergeSql\=true;druid.stat.slowSqlMillis\=5000
      # 配置DruidStatFilter
      web-stat-filter:
        enabled: true
        url-pattern: "/*"
        exclusions: "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"
      # 配置DruidStatViewServlet
      stat-view-servlet:
        url-pattern: "/druid/*"
        # IP白名单(没有配置或者为空,则允许所有访问)
        allow: 127.0.0.1,192.168.163.1
        # IP黑名单 (存在共同时,deny优先于allow)
        deny: 192.168.1.188
        #  禁用HTML页面上的“Reset All”功能
        reset-enable: false
        # 登录名
        login-username: admin
        # 登录密码
        login-password: 123456
mybatis:
  mapper-locations: classpath:mybatis/*.xml

3.springboot整合PageHelper
不需要做任何的配置文件,直接添加依赖即可使用,在查询全部之前调用:PageHelper.startPage(page,size);

<!--springboot整合pagehelper依赖启动器-->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.2.12</version>
</dependency>

4.springboot整合logback
springboot默认使用logback组件,作为日志管理,并且不需要添加任何依赖,spring-boot-starter-web包含了日志依赖;
只需将日志(logback.xml)放到resources目录下 名字必须叫logback.xml
logback.xml

<?xml version="1.0" encoding="UTF-8" ?>
 <configuration>
<!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径-->  
    <property name="LOG_HOME" value="${catalina.base}/logs/" />  
    <!-- 控制台输出 -->   
    <appender name="Stdout" class="ch.qos.logback.core.ConsoleAppender">
       <!-- 日志输出编码 -->  
        <layout class="ch.qos.logback.classic.PatternLayout">   
             <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符--> 
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n   
            </pattern>   
        </layout>   
    </appender>   
    <!-- 按照每天生成日志文件 -->   
    <appender name="RollingFile"  class="ch.qos.logback.core.rolling.RollingFileAppender">   
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--日志文件输出的文件名-->
            <FileNamePattern>${LOG_HOME}/server.%d{yyyy-MM-dd}.log</FileNamePattern>   
            <MaxHistory>30</MaxHistory>
        </rollingPolicy>   
        <layout class="ch.qos.logback.classic.PatternLayout">  
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息%n:换行符--> 
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n   
            </pattern>   
       </layout> 
        <!--日志文件最大的大小-->
       <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
         <MaxFileSize>10MB</MaxFileSize>
       </triggeringPolicy>
    </appender>     
    <!-- 日志输出级别 -->
    <root level="info">   
        <appender-ref ref="Stdout" />   
        <appender-ref ref="RollingFile" />   
    </root>
    <logger name="com.bjsxt.mapper" level="DEBUG"></logger>
</configuration>

5.springboot整合jsp
① 添加依赖

<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
    <scope>provided</scope>
</dependency>

②springboot不推荐使用jsp 如果想用jsp需要在main目录下创建一个webapp文件 并激活 在webapp下写jsp
在这里插入图片描述

③设置工作目录,如果idea中项目结构为聚合工程,需要在运行jsp指定路径 如上;如果是独立项目不需要
④在yml中配置视图解析器; (用来访问web-inf下的受保护的资源)
在这里插入图片描述
⑤在控制类中声明单元方法请求转发jsp资源
在这里插入图片描述

6.springboot整合 freemarker 它是一个.ftl文件
①导入依赖启动器

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

②把受保护的资源放到templates目录下; 开放的资源如:login.ftl放到public下;
③freemarker自带前缀和后缀 所以后台请求转发只需写 文件名即可(如:return:‘login’)
④插入值与el表达式类似 使用${}
⑤FTL指令 使用<#>
如 List集合遍历

<#list stus as stu>
    <tr><td>${stu_index+1}</td>
        <td>${stu.name}</td>
        <td>${stu.age}</td>
        <td>${stu.mondy}</td>
    </tr>
</#list>

map集合遍历 和if的使用

   <#--m:代表的是map集合  keys:map中key的集合   key:每一个key -->
    <#list m?keys as key>
        <#if stu_index%2==0>  <#--偶数设置成红色 -->
            <tr style="background-color: red">
        </#if>     
        <#if stu_index%2!=0>  <#--奇数设置成绿色 -->
            <tr style="background-color: green">
        </#if>
            <th>${key_index}</th>
            <th>${m[key].sname}</th>
            <th>${m[key].age}</th>
            <th>${m[key].sex}</th>
        </tr>
    </#list>

⑥freemarker取值不能为空 会报错
可以对其进行判空处理 :判断某变量是否存在使用 “??” 用法为:variable??,如果该变量存在,返回true,否则返回false 例:为防止stus为空报错可以加上判断如下:

<#if stus??>   <#--不存在 则返回false不执行里面的内容 -->
<#list stus as stu> 
...... 
</#list> 
</#if>

⑦内建函数
日期格式化:
显示年月日: t o d a y ? d a t e 显 示 时 分 秒 : {today?date} 显示时分秒: today?date{today?time}
显示日期+时间:${today?datetime}

自定义格式化: ${today?string(“yyyy年MM月”)}

⑧将json转化为字符串

<#assign text="{'bank':'工商银行','account':'10101920201920212'}" />   <#--assign 相当于定义了一个变量 字符串-->
<#assign data=text?eval />  													<#--通过 <#assigndata=text?eva/> 将字符串转化为json对象 -->
开户行:${data.bank} 账号:${data.account} 

7.springboot整合Thymeleaf
①引入依赖启动器

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

②它就是一个.html 文件
需要将html中标签改为
③它和freemarker一样 都是将受保护的页面写在templates下 公开的资源写在public下
④thymeleaf 接收数据都是以属性形式存在的
都是在标签内部 th:**=" ∗ " 不 能 直 接 用 {*}" 不能直接用 "{ }
⑤ if 判断 会显示 如果if 不成立 则此标签就不会显示
⑥ 循环遍历

<!-- ${li}:接受后台传递的集合     stu:集合中每一个对象  i为迭代状态   也可以不写 i -->
    <tr th:each="stu,i:${li}" th:class="${i.even}?a:b">  <!-- 三目运算 i.even 是否为偶数  -->
        <th th:text="${i.index}"></th>
        <th th:text="${stu.sname}"></th>
        <th th:text="${stu.age}"></th>

⑦a标签总href属性的使用
跳转二 getParam:路径 name是参数
⑧单击事件

删除 ⑨ 内置对象 大部分内置对象的名称都以s结尾。如:strings、numbers、dates 如: ${#strings.isEmpty(key)} 判断字符串key是否为空 ${#strings.contains(msg,'T')} 判断字符传是否包含T 日期格式化: ${#dates.format(key,'yyyy/MM/dd')}

8.使用开发者工具 作用:可以不用每次修改页面或者后台 都重启服务器 它会自动重启
①配置依赖启动器

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

② 设置idea自动编译
在这里插入图片描述
③ 修改Ctrl+Shift+Alt+/ 点击弹出框中Registry… 勾选: compiler.automake.allow.when.app.running

  1. 将springboot打包
    一:jar项目打包: 配置打包插件
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <fork>true</fork>
            </configuration>
        </plugin>
    </plugins>
</build>

点击右侧Maven – > Lifecycle --> clean–> install 将jar包粘贴至任意目录,可以直接运行因为内置tomacat
二: war项目:…
三: 部署到其他服务器(不适用自带的 tomcat)…

9.异常显示页面
======当出现异常时,它会自动跳往响应页面
① 设置具体的状态码页面 : 在templates下新建error文件,在error目录下新建 状态.html页面
例如: 500.html 名字要与异常数字一一对应
②可以使用X 模糊匹配
如: 出现 5 开头的状态错误码时, 显示页面可以命名为 5xx.html
③ 统一的错误显示页面:
在templates下新建 error.html 如果项目中不存在具体状态码页面时 都会跳往此页面

10.异常处理机制 : 解决异常问题 与springmvc中的异常处理机制一样 四种方式

11.springboot整合junit4
① 配置依赖启动器

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

②在src/main/test/java/下新建com.bjsxt.MyTest
注意:测试类不能叫test 测试方法必须是public 返回值必须是void 测试方法不能有参数
使用两个注解 @RunWith()

//告诉SpringBoot使用哪个单元测试工具
@RunWith(SpringJUnit4ClassRunner.class)
//当前类为测试类,classes指定哪个类为启动类
@SpringBootTest(classes = MyApplication.class)
public class MyTest {
    @Autowired
    UserMapper userMapper;
    @Autowired
    private UserService userService;
    @Test
    public void test(){
        User user = userMapper.selectById(1L);
        System.out.println(user);
        System.out.println(userService.test());
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值