Druid,Mybatis,Secruity学习

Druid

什么是Druid,有什么用?

Druid是Java语言中最好的数据库连接池连接数据库,Druid能够提供强大的监控扩展功能(监控 DB 池连接和 SQL 的执行情况,天生就是针对监控而生的 DB 连接池)

需要导入什么依赖
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.17</version>
</dependency>
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.12</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.6</version>
</dependency>
应该如何配置

查看官方文档或资料,看源码

spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource

    #Spring Boot 默认是不注入这些属性值的,需要自己绑定
    #druid 数据源专有配置
    # Druid 数据源配置,继承spring.datasource.* 配置,相同则覆盖
    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
如何进行监控

内置了Servlet,但是没有WEB.xml去注册,所以需要使用Springboot的方式去注册

package com.lcj.jdbc.configurate;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class druidConfigurate {
    /*
      将自定义的 Druid数据源添加到容器中,不再让 Spring Boot 自动创建
      绑定全局配置文件中的 druid 数据源属性到 com.alibaba.druid.pool.DruidDataSource从而让它们生效
      @ConfigurationProperties(prefix = "spring.datasource"):作用就是将 全局配置文件中
      前缀为 spring.datasource的属性值注入到 com.alibaba.druid.pool.DruidDataSource 的同名参数中
    */
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }
    
    @Bean
    public ServletRegistrationBean statViewServlet() {
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");

        // 这些参数可以在 com.alibaba.druid.support.http.StatViewServlet
        // 的父类 com.alibaba.druid.support.http.ResourceServlet 中找到
        Map<String, String> initParams = new HashMap<>();
        initParams.put("loginUsername", "dtt"); //后台管理界面的登录账号
        initParams.put("loginPassword", "123456"); //后台管理界面的登录密码

        //后台允许谁可以访问
        //initParams.put("allow", "localhost"):表示只有本机可以访问
        //initParams.put("allow", ""):为空或者为null时,表示允许所有访问
        initParams.put("allow", "");
        //deny:Druid 后台拒绝谁访问
        //initParams.put("kuangshen", "192.168.1.20");表示禁止此ip访问

        //设置初始化参数
        bean.setInitParameters(initParams);
        return bean;
    }
    //配置 Druid 监控 之  web 监控的 filter
//WebStatFilter:用于配置Web和Druid数据源之间的管理关联监控统计
    @Bean
    public FilterRegistrationBean webStatFilter() {
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());

        //exclusions:设置哪些请求进行过滤排除掉,从而不进行统计
        Map<String, String> initParams = new HashMap<>();
        initParams.put("exclusions", "*.js,*.css,/druid/*,/jdbc/*");
        bean.setInitParameters(initParams);

        //"/*" 表示过滤所有请求
        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }


}

过滤器同理

如何操作数据库

依旧使用JDBC(Springboot将JDBC操作数据库的方法都封装在JdbcTemplate jdbcTemplate)直接使用即可

注意

  • 创建集合对象需要设置初始值,同时创建对象

错误总结

解决java.nio.charset.MalformedInputException: Input length = 1(mybatis绑定失败的两个原因)

  • application.yml的编码问题,会导致去是添加resouce的配置(如下)时出现java.nio.charset.MalformedInputException: Input length = 1,mybatis也绑定不上。

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-2ZnQseHp-1625391054362)(C:\Users\LCJ\AppData\Roaming\Typora\typora-user-images\image-20210702101833071.png)]

lambok无法使用

  • ntellij idea 使用Lombok需要安装插件:Lombok plugin: Preferences —> Plugins —> 搜索 Lombok plugin — > Install
    同时设置 Preferences -> Compiler -> Annotation Processors -> Enable annotation processing勾选。
  • [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-U3AOaVHw-1625391054364)(C:\Users\LCJ\AppData\Roaming\Typora\typora-user-images\image-20210702114928472.png)]

Mybatis

什么是Mybatis,有什么用

MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作

需要导入什么依赖

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.1</version>
</dependency>
如何使用

官方文档:mybatis-spring-boot-autoconfigure – Introduction

您至少需要一个 sqlssessionfactory 和至少一个 mapper 接口

1.创建mapper接口

@Mapper
@Repository
public interface userMapper {
    List<User> getUsers();
}

2.配置XML

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.lcj.mabatis1.Mapper.userMapper"><!--mapper接口所在的位置-->

    <select id="getUsers" resultType="User"><!--mapper接口中的方法和返回结果-->
       select * from users;
   </select>
    <!--识别User以及我们的配置-->


</mapper>
3.识别User以及我们的配置–创建配置文件
mybatis:
  type-aliases-package: com.lcj.mabatis1.pojo
  mapper-locations: classpath:Mybatis/mapper/*.xml
4.创建控制器
@Controller
public class mybatisController {
    @Autowired
    private userMapper userMapper;
    @GetMapping("/select")
    @ResponseBody
    public List<User> getUsers(){
        List<User> users = userMapper.getUsers();
        return users;
    }
}

SpringSecurity

1.什么是SpringSecurity?有什么用?(拦截器,过滤器----简化—使用框架)
  • Springsecurity 是一个强大的、高度可定制的身份验证和访问控制框架。它是确保基于 spring 的应用程序安全的事实标准。

  • Springsecurity 是一个框架,它关注于为 Java 应用程序提供身份验证和授权。 像所有 Spring 项目一样,Spring Security 的真正威力在于它可以如何轻松地扩展以满足定制需求

  • Spring Security 是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型,他可以实现强大的Web安全控制,对于安全控制,我们仅需要引入 spring-boot-starter-security 模块,进行少量的配置,即可实现强大的安全管理!

记住几个类:

  • WebSecurityConfigurerAdapter:自定义Security策略
  • AuthenticationManagerBuilder:自定义认证策略
  • @EnableWebSecurity:开启WebSecurity模式

Spring Security的两个主要目标是 “认证” 和 “授权”(访问控制)。

“认证”(Authentication)

身份验证是关于验证您的凭据,如用户名/用户ID和密码,以验证您的身份

身份验证通常通过用户名和密码完成,有时与身份验证因素结合使用。

这个实例中验证你的身份是VIP几

“授权” (Authorization)

授权发生在系统成功验证您的身份后,最终会授予您访问资源(如信息,文件,数据库,资金,位置,几乎任何内容)的完全权限

这个实例中验证了你的身份授权给你相应的资源

2.需要导入什么依赖
		<dependency>
    	<groupId>org.springframework.boot</groupId>
    	<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<!thymeleaf-->
 		<dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-java8time</artifactId>
        </dependency>
		<!--Security-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
		<!--整合Security和thymeleaf-->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
3.如何配置

核心思想:看官方文档–看源码

官方文档:https://spring.io/guides/gs/securing-web/

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-C5Vvj1oJ-1625391054366)(C:\Users\LCJ\AppData\Roaming\Typora\typora-user-images\image-20210704164536112.png)]

源码:

*   protected void configure(HttpSecurity http) throws Exception {
*     http.authorizeRequests().antMatchers(&quot;/**&quot;).hasRole(&quot;USER&quot;).and().formLogin()
*           .usernameParameter(&quot;username&quot;) // default is username(前端传来的账户名和密码名字与默认一样)
*           .passwordParameter(&quot;password&quot;) // default is password
*           .loginPage(&quot;/authentication/login&quot;) // default is /login with an HTTP get
			(默认登录页是/login)
*           .failureUrl(&quot;/authentication/login?failed&quot;) // default is /login?error
*           .loginProcessingUrl(&quot;/authentication/login/process&quot;); // default is /login
*                                                     // with an HTTP
*                                                     // post
			进行身份验证默认/login
	 * The most basic configuration defaults to automatically generating a login page at
	 * the URL "/login", redirecting to "/login?error" for authentication failure. The
	 * details of the login page can be found on
		登录页面url(/login)
	 
	 * <li>/login GET - the login form</li>
	 * <li>/login POST - process the credentials and if valid authenticate the user</li>
	 通过POST请求/login(进行身份验证)
	 * <li>/login?error GET - redirect here for failed authentication attempts</li>
	 * <li>/login?logout GET - redirect here after successfully logging out</li>
	 * </ul>
	 *
package com.lcj.mabatis1.confirguate;
import org.springframework.context.annotation.Configuration;
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.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity(开启这个Security功能---Enablexxx)
public class SecurityConfir extends WebSecurityConfigurerAdapter {
    //重写方法configure(HttpSecurity http)
    //用于授权
    @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().loginPage("/toLogin").loginProcessingUrl("/login");
        //注销功能
        http.csrf().disable(); //关闭csrf功能,不关闭防跨站攻击则注销失败
        http.logout().logoutSuccessUrl("/"); //注销成功返回首页
        //记住我 参数与前端勾选框的name相对应
        http.rememberMe().rememberMeParameter("remember");
    }
    //认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //添加用户,设置密码编码
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                //设置root用户能访问所有页面
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                .and()
                //guest用户只能访问vip1页面
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1")
                .and()
                .withUser("dtt").password(new BCryptPasswordEncoder().encode("123456")).roles(("vip2"));

    }
}

清楚thymeleaf缓存

thymeleaf:
  cache: false

设置控制器进行跳转

编写前端页面

扩展

Rember实现

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-vEooZJ27-1625391054367)(C:\Users\LCJ\AppData\Roaming\Typora\typora-user-images\image-20210704162018213.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-jAoh0SYE-1625391054369)(C:\Users\LCJ\AppData\Roaming\Typora\typora-user-images\image-20210704165240522.png)]

两周时间

错误
  • 不清楚Security如何授权和认证

    授权:设置用户角色和相应的访问内容

    认证:添加用户并设置角色,对密码编码

    Secruity默认提供了一个登录页–我么也可以指定登录页

    输入账号和密码进行身份验证

    我们需要指定进行身份验证的URL(默认是/login)—post,登录页即处理请求页,也可以自定义处理请求页

    前端根据你的角色授权给你相应的内容

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值