整合JDBC
application.yaml
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
driver-class-name: com.mysql.cj.jdbc.Driver
#druid数据源配置
# 下面为连接池的补充设置,应用到上面所有数据源中
# 初始化大小,最小,最大
initial-size: 5
min-idle: 5
max-active: 20
# 配置获取连接等待超时的时间
max-wait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
time-between-eviction-runs-millis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
min-evictable-idle-time-millis: 300000
validation-query: SELECT 1 FROM DUAL
test-while-idle: true
test-on-borrow: false
test-on-return: false
# 打开PSCache,并且指定每个连接上PSCache的大小
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
# 配置监控统计拦截的 Filter,去掉后监控界面 SQL 无法统计,wall 用于防火墙 日志 log4j
filters: stat,wall,log4j #导入了log4j
use-global-data-source-stat: true
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
connect-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
JDBCController.java
@RestController
public class JDBCController {
@Autowired
private JdbcTemplate jdbcTemplate;
//查询数据库的所有信息
//没有实体类,数据库中的东西怎么获取
@RequestMapping("/userList")
public List<Map<String, Object>> userList() {
String sql = "select * from user";
List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
return maps;
}
//添加用户
@RequestMapping("/addUser")
public String addUser() {
String sql = "insert into user(id, name, age, email) values (5, '小兰', 23, '8951246532@qq.com')";
jdbcTemplate.update(sql);
return "addOk";
}
//修改用户
@RequestMapping("/updateUser/{id}")
public String updateUser(@PathVariable("id") Integer id) {
String sql = "update user set age = ?, email = ? where id = " + id;
Object[] objects = new Object[2];
objects[0] = "30";
objects[1] = "1111111111@qq.com";
jdbcTemplate.update(sql, objects);
return "updateOk";
}
//删除用户
@RequestMapping("/deleteUser/{id}")
public String deleteUser(@PathVariable("id") Integer id) {
String sql = "delete from user where id = ?";
jdbcTemplate.update(sql, id);
return "deleteOk";
}
}
DruidDataSource
Druid是阿里巴巴开源平台上一个数据库连接池,结合了C3P0,DBCP、PROXOOL等DB池的优点,同时加入了日志监控
SpringBoot2.0以上使用Hikari数据源,可以说Hikari与Durid都是当前Java Web上最优秀的数据源
导入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.2</version>
</dependency>
DruidConfig
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDataSource() {
return new DruidDataSource();
}
//后台监控
//因为SpringBoot内置了servlet容器,所以没有web.xml,替代方法ServletRegistrationBean
@Bean
public ServletRegistrationBean a() {
ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
//后台需要有人登录,账号密码配置
HashMap<String, String> map = new HashMap<>();
//增加配置
map.put("loginUsername", "admin");//登录的key是固定的 loginUsername loginPassword
map.put("loginPassword", "123");
//允许可以访问的
map.put("allow", "localhost");//允许本机可以访问
//禁止访问
// map.put("www", "写你的ip");
bean.setInitParameters(map);
return bean;
}
//filter
@Bean
public FilterRegistrationBean b() {
FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
bean.setFilter(new WebStatFilter());
//可以过滤哪些请求
HashMap<String, String> map = new HashMap<>();
//不拦截
map.put("exclusive", "*.js, *.css, /druid/*");
bean.setInitParameters(map);
return bean;
}
}
SpringSecurity
Spring Security是针对Spring项目的安全框架,也是SpringBoot底层安全模块默认的技术类型,它可以实现强大的web安全控制,只需要引入spring-boot-start-security模块,进行少量的配置
重要的类:
- WebSecurityConfigurerAdapter:自定义Security策略
- AuthenticationManagerBuilder:自定义认证策略
- @EnableWebSecurity:开启WebSecurity模式
Spring Security的两个主页目标是“认证”和“授权”
导包
<!-- security-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
认证之前要先进行授权,给角色授权,给用户认证,并且在进行认证中的密码阶段,要先进行加密,和加密编码
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//授权
@Override
protected void configure(HttpSecurity http) throws Exception {
//设置访问的权限
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");
//没有权限默认到登录页面,开启默认的登录页面
// http.formLogin();
//手动设置登录页面
http.formLogin()
.loginPage("/toLogin")//虽然走的时login的url,但实际显示的是toLogin的页面,即通过login到toLogin的页面
.loginProcessingUrl("/login");
// .usernameParameter("user")//当username和password不是默认的名称时,比如自定义的是user和pwd可以通过这种方式实现(类似起别名)
// .passwordParameter("pwd");
//注销
http.logout().logoutSuccessUrl("/");//跳到首页
http.logout().deleteCookies("remove").invalidateHttpSession(true);//移除cookie
//关闭csrf功能,否则会注销失败
http.csrf().disable();
//记住我,cookie,session,默认保存2周
// http.rememberMe();
//自定义页面记住我
http.rememberMe().rememberMeParameter("remember");//remember是自定义时的name属性
}
//认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// auth.jdbcAuthentication() 数据库认证
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())//内存认证
.withUser("www").password(new BCryptPasswordEncoder().encode("123")).roles("vip1")//使用密码前要进行加密,并且使用密码时,要进行加密编码
.and()//可以用来连接多个用户
.withUser("root").password(new BCryptPasswordEncoder().encode("root")).roles("vip1", "vip2", "vip3");
}
}
thymeleaf和security整合(此时的boot降级到2.0.9)
导包
<!-- security和thymeleaf整合-->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>