所有的

springboot


1.logback日志框架
2.webjars静态资源映射
3.Thymeleaf模板引擎


层级关系要显示清楚,在设置里有一个
compact middle package 把勾去掉


用于标识springboot启动类
@SpringBootApplication
    底层是3个组件:@springbootConfiguration
                   @EnableAutoConfiguration
                   @ComponentScan


jar包运行,打好jar包,控制台可以看到jar包存放路径
cd C:\Users\Administrator\Desktop
java -jar springboot-hello-SNAPSHOT.jar

validator
数据校验器

quartz
定时器

springboot各种组件依赖
https://docs.spring.io/spring-boot/docs/2.0.6.RELEASE/reference/htmlsingle/#using-boot-starter


springboot启动类要与controller,service这些包同级,属于同一个包下,启动时才能扫描到那些东西里的组件
 

 

 

springboot启动类要与controller,service这些包同级,属于同一个包下,启动时才能扫描到那些包里的组件,也能扫描到与启动类同级的类。(可以扫描到兄弟的儿子,和自己的兄弟,不能扫描到爸爸的兄弟的儿子)

yml配置文件语法特别注意list数组元素的 - 后面也要有空格
  list:
    - one
    - two

Alt+insert  快捷键set和get方法和tostring()    生成

@ConfigurationProperties(prefix = "emp" ) 一般放在组件类上的注解 可以将application.yml或application.properties这两个全局配置文件中的属性和组件类中的属性一一对应绑定,emp是某前缀名,可以去搜寻yml中的这个属性前缀
@Component 把当前组件收纳为springboot管理


测试类里需要有@RunWith(SpringRunner.class) 可以把所有组件都直接扫描到来运行

配置文件有中文:
settings里的file encodings修改

@Value 可以替代@ConfigurationProperties 来在实体类中获取到配置文件里对应属性的值
@Value("${emp.name}") 或者是spring表达式直接赋值  @Value("#{20}") / @Value("20")

 

@Value   和  @ConfigurationProperties  的区别对比

     @Value    @ConfigurationProperties
松散绑定语法(大小写有区别或者有符号)    不支持    支持
spel(spring表达式,比如一些运算)    支持    不支持
复杂类型封装(比如map,list)    不支持    支持
JSR303数据校验(@Validated+@Email)    不支持    支持
 

总结:少量的不涉及复杂类型封装和数据校验的用@Value,其他都用@ConfigurationProperties

 

新创建的局部配置文件与组件类绑定的注解
@PropertySource(value = {"classpath:emp.properties"})


想要加载xml的信息,在主配置类(也就是springboot启动类)上添加注解
@ImportResource(locations ={"classpath:spring01.xml "} )


yml可以通过 --- 分成块,每块都可以有各自的配置,相同的配置也可以

profile多环境支持
第一种:yml全局配置格式

spring
  profiles:
    active: xx

第二种:
在项目里的Environment的program arguments写上
spring.profiles.active=xx

第三种:jar包
运行jar包命令后加 --spring.profiles.active=xx

配置文件的默认扫描级别(从高到低)

工程的config的properties
工程的properties
resources的config的properties
resources的properties

备注:如果有多个工程,放在当前工程下的properties或config里的properties在被扫描时会扫描到第一个工程的工作目录,所以
当前工程的配置文件路径
在项目里的Environment的Working directory写上
$MODULE_DIR$

 

配置文件属性网址

https://docs.spring.io/spring-boot/docs/2.0.6.RELEASE/reference/htmlsingle/#common-application-properties
 

 

日志框架logback          上层的抽象层slf4j

日志级别由低到高:trace<debug<info<warn<error
springboot默认为info级别,比它低级别的就不显示了,因为不重要


修改某个包日志级别:
properties配置文件中,如果是yml对应修改
logging.level.com.mengxuegu=debug
包名=级别

修改springboot日志级别:
properties配置文件中,如果是yml对应修改
logging.level.root=debug


日志输出的两个配置

logging.file    logging.path    配置示例    说明
指定文件名    none    
springboot.log

或者D:/springboot.log

输出到当前根目录下的springboot.log

或者指定磁盘路径

none    指定目录    /springboot/log    输出到当前项目所在磁盘根目录下的/springboot/log/的新创建的spring.log中
两个都配置时         执行logging.file的配置,也是springboot推荐配置,因为logging.file也可以指定磁盘路径完成logging.path的功能
踩坑:较新版本springboot已经将logging.file修改为logging.file.name

                                      将logging.path修改为logging.file.path

 

修改控制台日志输出格式:

logging.pattern.console=%d{yyyy-MM-dd} == [%thread] == %-5level == %logger{50} - %msg%n

 

修改日志文件输出格式:

logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss.SSS} >>> [%thread] >>> %-5level >>> %logger{50} >>> %msg%n

 

springboot规定使用logback框架的配置文件名是logback.xml,放在resources下

其他框架的配置文件名和放置位置可以查看官方文档,网址:

https://docs.spring.io/spring-boot/docs/2.0.6.RELEASE/reference/htmlsingle/#boot-features-logging

 

多环境下的日志自定义,需要用logback-spring.xml这个名称
放在logback-spring.xml的第一个layout里面可以配置不同环境下的日志输出格式

<springProfile name="dev">
                <!-- configuration to be enabled when the "staging" profile is active -->
                <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} - [%thread] - %-5level - %logger{50} - %msg%n</pattern>
            </springProfile>

properties中也要对应配置profiles配置

 

默认是logback日志框架,切换成log4j2日志框架:

https://docs.spring.io/spring-boot/docs/2.0.6.RELEASE/reference/htmlsingle/#boot-features-logging

找到13.5 Starters  

找到spring-boot-starter-log4j2
在pom里替换掉spring-boot-starter-logging
 

输出某日志

Logger logger = LoggerFactory.getLogger(getClass());
logger.info("xxx");
 

 

 

webjars官网

webjars.org

引入依赖

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>jquery</artifactId>
    <version>3.3.1</version>
</dependency>


静态资源的获取目录(js或者css)
"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/
欢迎页index.html      图标ico    
"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/
+
和根目录路径
 

 

引入Thymeleaf依赖
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>


html里的动态text示例
先加上这个命名空间格式
<html lang="en" xmlns:th="http://www.thymeleaf.org">

<hr/>
<p th:text="${name}"></p>

引入公共片段
被别人引入的header.html
<div th:fragment="header_common">这是声明公共片段</div>
去引入别人的
<div th:replace="header :: header_common"></div>

与th:replace相似的是th:insert
区别:使用th:insert,公共片段的标签和当前标签都会保留,而th:replace会将公共片段的标签全部覆盖当前标签
 

 

th:each迭代,有多少个key就迭代多少次
<tr th:each="user:${list对象}
<td th:text="${list对象的key}
<td th:text="${list对象的value}

如果只需要遍历出key
<li th:each="user : ${list对象}" th:text="${list对象的key}"></li>

user是第一个值,也有第二个值iterStat,(这里只是举例,名字随便取),第二个值有以下属性
index : 当前迭代下标 0 开始
            count : 当前迭代下标 1 开始
            size  : 获取总记录数
            current : 当前迭代出的对象
            even/odd : 当前迭代是偶数还是奇数 (1开始算,返回布尔值)
            first : 当前是否为第一个元素
            last : 当前是否为最后一个元素

总结:第二个值主要是可以得到记录数,奇偶数这些遍历出来记录的属性

th:if  动态判断,来决定显不显示标签内容

<h3 th:if="not ${#lists.isEmpty(list对象)}">显示出来说明不空</h3>

th:switch  动态指向

<div th:switch="${map的key}">
       <P th:case="1">value1</P>
       <P th:case="2">value2</P>

th:utext
可以不转义特殊字符,展现它的效果

th:Object  可以直接取出对象


开发环境中使用thymeleaf的热部署
依赖:
<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        </dependency>

properties里
springspring.thymeleaf.cache=false

热部署需要写完后按ctrl+F9

 

 

html
<tr  行
   <td  单元格
   <th  加粗字体单元格
<ul  无序列表
   <li   列表项
<hr  横线
  <h3 标题标签 
<br   换行符
 

 

自定义springmvc的配置

配置类 实现 WebMvcConfigurer类
类上用@Configuration是配置类
类上用@EnableWebMvc来使springboot对springmvc的自动配置都失效

总结 SpringMVC 配置:
进公司拿到项目之后,在Spring Boot中自已配置组件的时候,先看容器中有没有公司自已配置的
(@Bean、@Component),如果
有就用公司自已配置的; 如果没有,才自动配置。


阿里云
284085


密码:kA2GYmE4cJgiSLE0

wget http://mirror.bit.edu.cn/apache/maven/maven-3/3.3.9/binaries/apache-maven-3.3.9-
bin.tar.gz


部署了一个网站,可以访问一下
http://47.115.152.213:8080/
账户:root
密码:123
 

获取当前日期的html

<html>
<head>
<title>
</title>
</head>
<body>
<!--
获得当前日期(年月日)并显示在段落内
-->
    <p id="ymd"></p>
    <script>
        var date = new Date()<!--获得日期数据-->
        var y = date.getFullYear();<!--年-->
        var m = date.getMonth()+1;<!--月,这里的月份必须要+1才是当前月份-->
        var d = date.getDate(); <!--日,getDay是获得当前星期几(0-6),getDate是获得当前日
期-->
        document.getElementById("ymd").innerHTML = "更新时间:"+y+"-"+m+"-"+d;
    </script>
    <script type="text/javascript" src="dtxt1.js"></script>
</body>
</html>

 

 

判断密码为123且用户名不为空
if (!StringUtils.isEmpty(username)&& "123".equals(password))


用户名密码输错了,显示的报错字体
th:if="${not #strings.isEmpty(msg)}" th:text="${msg}"

拦截/xx未登录请求
现在login的控制层设置一个HttpSession session变量,用于装是否登录信息
如果登陆了给session一个值,即session为空,就是未登录
session.setAttribute("loginUser", username);

interceptor包下
public class LoginHandlerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse
response, Object handler) throws Exception {
            Object loginUser = request.getSession().getAttribute("loginUser");
                if( loginUser != null) {
                return true;
        }
        request.setAttribute("msg", "没有权限,请先登录!");
        //因为要带上面那条提示信息
        request.getRequestDispatcher("/index.html").forward(request, response);
        return false;
    }
}

以上是定义登录拦截器,把它交给springboot管理
在config包下
@Configuration
public class MySpringMvcConfigurer {
    @Bean
    public WebMvcConfigurer webMvcConfigurer() {
        return new WebMvcConfigurer(){
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                registry.addInterceptor(new LoginHandlerInterceptor())
                        //指定要拦截的请求 /** 表示拦截所有请求
                        .addPathPatterns("/**")
                        //排除不需要拦截的请求路径
                        .excludePathPatterns("/", "/index.html", "/login")
                        //springboot2+之后需要将静态资源文件的访问路径 也排除
                        .excludePathPatterns("/css/*", "/img/*","/js/*");
            }
        };

获取访问的用户名(hi,xx)
[[${session.loginUser}]]


退出系统,loginController里面创建一个方法
th:href="@{/logout}"


session的方法:
setAttribute     存入信息
removeAttribute  移除信息
invilidate       销毁session

RestFul架构:请求URI:/资源名称/资源标识
查询:   xx - GET
添加     xx - POST
修改     xx - PUT
添加     xx - DELETE


@Repository注解用于dao层的类标识为springboot的bean,交给springboot管理

两个参数注解
2("pid") Integer pid             和mapping("xx/pid")一致
@RequestParam(value = "providerName", required = true,defaultValue = "view") String providerName        mvc中传入参数

ps:@RequestParam注解中,没写defaultValue时,required默认为true;写了defaultValue时可以不用写required本身
ps:@PAthVariable  通常用在查询,修改,删除方法中获取记录的唯一id的注解


信息回显:
th:value="{$provider.xx}"

修改资源路径
th:href="@{/provider/} + ${p.pid}"

<form  表单的模板
th:action="@{/provider}"


修改信息方法注解
@PutMapping(“/provide/{pid}”)


添加信息方法注解
@PostMapping("/provide{pid}")


删除信息方法注解
@DeleteMapping("/provide{pid}")
 

 

绑定属性
th:attr="del_uri=@{/provider/}+${p.pid}"

springboot1.0,2014年发布,默认数据库连接池为 Tomcat JDBC Pool
springboot2.0,2018年3月1日发布,默认数据库连接池为  Hikari


1.项目创建选择组件:mysql,jdbc    web

application.yml里:

spring:
datasource:
username: root
password: root
#使用 MySQL连接驱动是8.0以上,需要在Url后面加上时区, GMT%2B8代表中国时区,不然报时区
错误
url: jdbc:mysql://127.0.0.1:3306/jdbc?serverTimezone=GMT%2B8
# 注意: 新版本驱动包,要使用以下类作为驱动类
driver-class-name: com.mysql.cj.jdbc.Driver


@RestController注解=@Controller+@ResponseBody

druid

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>

mybatis
创建项目    选择mybatis,jdbc,mysql   web


@MapperScan("com.mengxuegu.springboot.mapper")会自动装配指定包下面所有Mapper,省得在
每个Mapper上面写@Mapper

Mybatis官网: http://www.mybatis.org/mybatis-3/zh/index.html
mybatis通常用xml方式,小项目才用注解方式

在 resources 创建以下目录和核心配置文件mybatis-config.xml与mapper映射文件夹
mapper下一般装xxmapper.xml

mybatis-config.xml里加上驼峰映射
<configuration>
    <!--核心配置文件-->
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>


application.yml里

#配置mybatis相关文件路径
mybatis:
  #映射配置文件路径
  mapper-locations: classpath:mybatis/mapper/*.xml
  #核心配置文件路径
  config-location: classpath:mybatis/mybatis-config.xml

IOexception
servletexception
SQLException
InterruptedException
MessagingException
UnknownHostException
RuntimeException
 

 

@Entity //说明 它是和数据表映射的类
@Table(name = "tbl_user") //指定对应映射的表名,省略不写默认表名是类同 user


jpa里的注解
@Id //指定主键
@GeneratedValue(strategy = GenerationType.IDENTITY)    主键自增长注解

@Column(name = "user_name",length = 5) //这是和数据表对应的一个列,如果省略括号里的列名,就默认为下面的属性名

jpa结构:
实体类;
dao接口: 创建 UserRepository 接口继承 JpaRepository , 就会crud及分页等基本功能
JpaRepository<实体类,id的类型>


yml全局配置
# jpa相关配置 spring.jpa.*
jpa:
# 控制台显示SQL
showSql: true
hibernate:
# 会根据就映射实体类自动创建或更新数据表,这里已经创建了,就不用create
ddl-auto: update
# 默认创建表类型是MyISAM,是非事务安全的,所以无法实现事物回滚
# 指定如下方言: 创建的表类型是Innodb,才可以进行对事物的回滚。
database-platform: org.hibernate.dialect.MySQL5InnoDBDialect

事务管理步骤:
1. 在启动类上 ,使用 @EnableTransactionManagement 开启注解方式事务支持
2. 在 Service层方法上添加 @Transactional 进行事务管理

 

 

快捷键Shift+F6 重命名


@EnableAysnc 在启动类上开启基于注解的异步任务
@Aysnc     在service里的方法上的注解,标识后的方法会异步执行


@EnableScheduling 启动类上开启基于注解的定时任务

@Scheduled 标识的方法会进行定时处理,该注解的属性是cron=xx
在线生成cron表达式 http://cron.qqe2.com/

选择组件时:Core里的Cache
@EnableCaching:在启动类上,开启基于注解的缓存
@Cacheable : 标在方法上,返回的结果会进行缓存(先查缓存中的结果,没有则调用方法并将结果放到缓存中),
该注解的属性有value/cacheNames  :缓存的名字key : 作为缓存中的Key值,可自已使用 SpEL表达式指定(不指定就是参数值), 缓存结果是方法返回@CachePut    缓存更新
@CacheEvict   清除缓存
@CacheConfig(cacheNames = “user”) 指定缓存公共属性值 ,指定在类上,其他方法上就不需要写缓存名。
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值