7.Druid数据源
Druid是一个阿里推出的数据源,可以用来拦截,监视sql,或防止sql注入等功能强大的数据源,依赖如下:
<!-- alibaba的druid数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.9</version>
</dependency>
然后在SpringBoot下的配置文件application.yml配置数据源:
spring:
thymeleaf:
cache: false
prefix: classpath:/templates/
suffix: .html
#国际化
messages:
basename: i18n.login
#数据库配置
datasource:
name: test
url: jdbc:mysql://localhost:3306/project?serverTimezone=GMT%2B8&useSSL=true
username: root
password: 98526
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
#druid数据源的专有配置,SpirngBoot默认是不注入这些值的需要自己绑定
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
#配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
#如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority
#则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
然后在SpringBoot的配置类中在进行绑定如:
//WebMVc扩展配置类
@Configuration
public class WebConfig implements WebMvcConfigurer {
//绑定Druid数据源
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource druidDataSource() {
return new DruidDataSource();
}
}
同时也可以进行配置后台监控,在Druid有自己写的页面进行监控sql代码,只需要进行配置就可以查看了如:
//WebMVc扩展配置类
@Configuration
public class WebConfig implements WebMvcConfigurer {
//后台监控配置配置
@Bean
public ServletRegistrationBean<StatViewServlet> statViewServlet() {
ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
//配置
HashMap<String, String> initParameters = new HashMap<>();
initParameters.put("loginUsername", "admin");
initParameters.put("loginPassword", "98526");
//允许谁能访问 initParameters.put("allow","");
//禁止谁能访问 initParameters.put("xiaobu","172.1.5.68" );
bean.setInitParameters(initParameters);
return bean;
}
}
8.整合mybaits
SpringBoot整合myBaits只需要进行导入mybais的包在加以配置就可以使用了:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
在主配置ymal中配置:
## 该配置节点为独立的节点,不能放在spring的节点下,否则导致配置无法被识别
mybatis:
# 加载全局的配置文件
configLocation: classpath:MyBatis/mybaits-config.xml
#配置Mapper.xml位置
mapper-locations: classpath:MyBatis/**/*Mapper.xml
#起别名
type-aliases-package: com.example.springboot4.project.*.**
Mapper的映射类等使用以下注解:
@Mapper //表示xml的映射类
@Service //注册bean
9.Spring Security(安全)
简介:
Spring Security,这是一种基于 Spring AOP 和 Servlet 过滤器的安全框架。它是针对SpringBoot项目的安全框架,也是SpringBoot底层安全模块默认的技术选型,他可以实现强大的Web安全控制,我们也仅仅只需要导入他的依赖,就可以实现少量的配置实现强大的安全管理与Spring Security相同的还有Shiro等待安全校验的框架。
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>5.7.1</version>
</dependency>
记住Spring Security几个类:
- WebSecurityConfigurerAdapter:自定义Security策略
- AuthenticationManagerBuilder:自定义认证策略
- @EnableWebSecurity:开启WebSecurity模式
Spring Security的两个主要目标就是“认证”和“授权”(访问控制)
这个概念是通用的,而不是只在Spring Security中存在
基本使用如下:
package com.example.springsecurity.config;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//请求控制
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
//首页都可以访问
.antMatchers("/").permitAll()
//level1请求下的只有vip1才能访问
.antMatchers("/level1/**").hasRole("vip1")
//level2请求下的只有vip2才能访问
.antMatchers("/level2/**").hasRole("vip2")
//level3请求下的只有vip3才能访问
.antMatchers("/level3/**").hasRole("vip3");
//没有权限默认会跳转到登录页面,需要开启登录页面
http.formLogin();
//注销,注销成功返回首页
http.logout().logoutUrl("/");
}
//认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//这些数据正常应该从数据库中读取
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("xiaobu").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
.and()
.withUser("xiaoqi").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2")
.and()
.withUser("xiaoba").password(new BCryptPasswordEncoder().encode("123456")).roles("vip3");
}
}
而如果想要在页面上展示用户当前权限有的功能,权限没有的功能不展示则需要导入security与thymeleaf整合的包
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
在页上使用需事先声明如:
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
实例:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>首页</title>
<!--semantic-ui-->
<link href="https://cdn.bootcss.com/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet">
<link th:href="@{/qinjiang/css/qinstyle.css}" rel="stylesheet">
</head>
<body>
<!--主容器-->
<div class="ui container">
<div class="ui segment" id="index-header-nav" th:fragment="nav-menu">
<div class="ui secondary menu">
<a class="item" th:href="@{/index}">首页</a>
<!--登录注销-->
<div class="right menu">
<!--未登录-->
<a class="item" th:href="@{/toLogin}" sec:authorize="!isAuthenticated()">
<i class="address card icon"></i> 登录
</a>
<!-- 已登陆 -->
<a class="item" sec:authorize="isAuthenticated()">
用户名: <span sec:authentication="name"></span>
角色: <span sec:authentication="principal.getAuthorities()"></span>
</a>
<a class="item" th:href="@{/logout}" sec:authorize="isAuthenticated()">
<i class="sign-out icon"></i> 注销
</a>
<!--已登录
<a th:href="@{/usr/toUserCenter}">
<i class="address card icon"></i> admin
</a>
-->
</div>
</div>
</div>
<div class="ui segment" style="text-align: center">
<h3>Spring Security Study by 秦疆</h3>
</div>
<div>
<br>
<div class="ui three column stackable grid">
<div class="column">
<div class="ui raised segment">
<div class="ui">
<div class="content">
<h5 class="content">Level 1</h5>
<hr>
<div><a th:href="@{/level1/1}"><i class="bullhorn icon"></i> Level-1-1</a></div>
<div><a th:href="@{/level1/2}"><i class="bullhorn icon"></i> Level-1-2</a></div>
<div><a th:href="@{/level1/3}"><i class="bullhorn icon"></i> Level-1-3</a></div>
</div>
</div>
</div>
</div>
<div class="column">
<div class="ui raised segment">
<div class="ui">
<div class="content">
<h5 class="content">Level 2</h5>
<hr>
<div><a th:href="@{/level2/1}"><i class="bullhorn icon"></i> Level-2-1</a></div>
<div><a th:href="@{/level2/2}"><i class="bullhorn icon"></i> Level-2-2</a></div>
<div><a th:href="@{/level2/3}"><i class="bullhorn icon"></i> Level-2-3</a></div>
</div>
</div>
</div>
</div>
<div class="column">
<div class="ui raised segment">
<div class="ui">
<div class="content">
<h5 class="content">Level 3</h5>
<hr>
<div><a th:href="@{/level3/1}"><i class="bullhorn icon"></i> Level-3-1</a></div>
<div><a th:href="@{/level3/2}"><i class="bullhorn icon"></i> Level-3-2</a></div>
<div><a th:href="@{/level3/3}"><i class="bullhorn icon"></i> Level-3-3</a></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script th:src="@{/qinjiang/js/jquery-3.1.1.min.js}"></script>
<script th:src="@{/qinjiang/js/semantic.min.js}"></script>
</body>
</html>